问题 C: 聚会

时间限制: 10 Sec  内存限制: 64 MB
提交: 21  解决: 8
[提交][状态][讨论版][
命题人:add_lm][Edit] [TestData]

题目链接:http://acm.ocrosoft.com/problem.php?cid=1691&pid=2

题目描述

Y岛风景美丽宜人,气候温和,物产丰富。Y岛上有N个城市,有N-1条城市间的道路连接着它们。每一条道路都连接某两个城市。幸运的是,小可可通过这些道路可以走遍Y岛的所有城市。神奇的是,乘车经过每条道路所需要的费用都是一样的。小可可,小卡卡和小YY经常想聚会,每次聚会,他们都会选择一个城市,使得3个人到达这个城市的总费用最小。 由于他们计划中还会有很多次聚会,每次都选择一个地点是很烦人的事情,所以他们决定把这件事情交给你来完成。他们会提供给你地图以及若干次聚会前他们所处的位置,希望你为他们的每一次聚会选择一个合适的地点。

输入

第一行两个正整数,NM。分别表示城市个数和聚会次数。后面有N-1行,每行用两个正整数AB表示编号为A和编号为B的城市之间有一条路。城市的编号是从1N的。再后面有M行,每行用三个正整数表示一次聚会的情况:小可可所在的城市编号,小卡卡所在的城市编号以及小YY所在的城市编号。

输出

一共有M行,每行两个数PosCost,用一个空格隔开。表示第i次聚会的地点选择在编号为Pos的城市,总共的费用是经过Cost条道路所花费的费用。

样例输入

6 4

1 2

2 3

2 4

4 5

5 6

4 5 6

6 3 1

2 4 4

6 6 6

样例输出

5 2

2 5

4 1

6 0

提示
100%的数据中,N<=500000M<=500000
40%的数据中N<=2000M<=2000

思路:倍增求lca,两两求lca减一减即可

代码:

#include<bits/stdc++.h>

using namespace std;

const int maxn = 500005;

int First[maxn], Next[maxn * 2], v[maxn * 2], st[maxn][23], Fa[maxn], num_edge;

int dep[maxn];

void ins(int x, int y)//建边

{

    v[++num_edge] = y;

    Next[num_edge] = First[x];

    First[x] = num_edge;

}

void dfs(int x, int fa)//无向图中需要记录父节点防止死循环

{

    Fa[x] = fa;

    for (int i = First[x]; i != -1; i = Next[i])

    {

         int to = v[i];

         if (to == fa)continue;

         dep[to] = dep[x] + 1;

         dfs(to, x);

    }

}

int get_lca(int x, int y)

{

    if (dep[x] < dep[y])swap(x, y);//确定x的深度比y大,方便处理

    //得到同一深度

    for (int i = 20; i >= 0; i--)

    {

         if (dep[st[x][i]] >= dep[y])

         {

             x = st[x][i];

         }

    }

    //若此时两者节点相同,说明y就是x和y的公共祖先

    if (x == y)return x;

    //一起往上跳

    for (int i = 20; i >= 0; i--)

    {

         if (st[x][i] != st[y][i])

         {

             x = st[x][i];

             y = st[y][i];

         }

    }

    //公共祖先就是其父节点

    return st[x][0];

}

int main()

{

    int n, q;

    cin >> n >> q;

    memset(First, -1, sizeof(First));

    for (int i = 1; i < n; i++)

    {

         int x, y;

         scanf("%d %d", &x, &y);

         ins(x, y), ins(y, x);

    }

    dep[1] = 1;//初始化根节点深度

    dfs(1, 0);

    for (int i = 1; i <= n; i++)

    {

         st[i][0] = Fa[i];

    }

    for (int i = 1; i <= 20; i++)

    {

         for (int j = 1; j <= n; j++)

         {

             st[j][i] = st[st[j][i - 1]][i - 1];

         }

    }

    while (q--)

    {

         int x, y, z;

         scanf("%d %d %d", &x, &y, &z);

         //cin >> x >> y >> z;

         int t1 = get_lca(x, y), t2 = get_lca(x, z), t3 = get_lca(z, y);

         int pos;

         if (t1 == t2)

             pos = t3;

         else if (t1 == t3)

             pos = t2;

         else

             pos = t1;

         printf("%d %d\n", pos, dep[x] + dep[y] + dep[z] - dep[t1] - dep[t2] - dep[t3]);

    }

}