codeforces 832D Misha, Grisha and Underground 最近公共祖先LCA

Input
The first line contains two integers n and q (2 ≤ n ≤ 105, 1 ≤ q ≤ 105) — the number of stations and the number of days.

The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi ≤ n). The integer pi means that there is a route between stations pi and i. It is guaranteed that it's possible to reach every station from any other.

The next q lines contains three integers a, b and c each (1 ≤ a, b, c ≤ n) — the ids of stations chosen by boys for some day. Note that some of these ids could be same.

Output
Print q lines. In the i-th of these lines print the maximum possible number Grisha can get counting when the stations s, t and f are chosen optimally from the three stations on the i-th day.

Examples
input
3 2
1 1
1 2 3
2 3 3
output
2
3
input
4 1
1 2 3
1 2 3
output
2

分析:给3个点任选一个作为终点其他两个为起始点,求两条路径相交的最大值。

求树上的路径可以用LCA。求两条路径的相交长度 为:(d(a,b) + d(c,b) - d(a,c)) /2  其中b为终点---这两条的路径必有相交点所以有此公式。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<vector>
#include<cmath>
#include<queue>
using namespace std;

int n,q;
vector<int> e[100005];
int fa[100005][22];
int dep[100005];

void dfs(int u,int f,int d)
{
    fa[u][0]=f;
    dep[u]=d;
    int len=e[u].size();
    for(int i=0;i<len;i++)
    {
        int v=e[u][i];
        if(v!=f)
        {
            dfs(v,u,d+1);
        }
    }
}

void init()
{
    for(int i=1;i<=20;i++)
    {
        for(int j=1;j<=n;j++)
        {
            fa[j][i]=fa[fa[j][i-1]][i-1];
        }
    }
}

int LCA(int a, int b)
{
    if(dep[a]<dep[b])
        swap(a,b);

    int c=dep[a]-dep[b];
    for(int i=20;i>=0;i--)
    {
        if((c&(1<<i))!=0)
        {
            a=fa[a][i];
        }
    }
    if(a==b)
        return b;

    for(int i=20;i>=0;i--)
    {
        if(fa[a][i]!=fa[b][i])
            a=fa[a][i],b=fa[b][i];
    }
    return fa[a][0];

}
int dis(int a,int b)
{
    int lca=LCA(a,b);
    return dep[a]+dep[b]-2*dep[lca];
}
int solve(int a,int b,int c)
{
    return (a+b-c)/2+1;
}

int main()
{
    while(~scanf("%d%d",&n,&q))
    {
        for(int i=0;i<=100000;i++)
        {
            e[i].clear();
            for(int j=0;j<=20;j++)
                fa[i][j]=0;
        }
        for(int i=2;i<=n;i++)
        {
            int tp;
            scanf("%d",&tp);
            e[tp].push_back(i);
            e[i].push_back(tp);
        }
        dfs(1,0,0);
        init();

        //cout<<LCA(2,4)<<endl;
        while(q--)
        {
            int a,b,c;
            scanf("%d%d%d",&a,&b,&c);
            int d1=dis(a,b);
            int d2=dis(b,c);
            int d3=dis(a,c);

            int ans1=solve(d1,d2,d3);
            int ans2=solve(d2,d3,d1);
            int ans3=solve(d1,d3,d2);

            int ans=max(max(ans1,ans2),ans3);
            printf("%d\n",ans);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/c_czl/article/details/85109643