Codeforces 832D - Misha, Grisha and Underground

Posted Wisdom+.+

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Codeforces 832D - Misha, Grisha and Underground相关的知识,希望对你有一定的参考价值。

832D - Misha, Grisha and Underground

思路:lca,求两个最短路的公共长度。公共长度公式为(d(a,b)+d(b,c)-d(a,c))/2。

代码:

#include<bits/stdc++.h>
using namespace std;
#define ll long long 
#define ls rt<<1,l,m
#define rs rt<<1|1,m+1,r
const int INF=0x3f3f3f3f;
const int N=1e5+5;
const int logn=20;
vector<int>g[N];
int anc[logn][N];
int deep[N];
void dfs(int o,int u)
{
    deep[u]=deep[o]+1;
    for(int j=0;j<g[u].size();j++)
    {
        if(g[u][j]!=o)
        {
            anc[0][g[u][j]]=u;
            for(int i=1;i<logn;i++)anc[i][g[u][j]]=anc[i-1][anc[i-1][g[u][j]]];
            dfs(u,g[u][j]);
        }
    }
}
int lca(int u,int v)
{
    if(deep[u]<deep[v])swap(u,v);
    for(int i=logn-1;i>=0;i--)if(deep[anc[i][u]]>=deep[v])u=anc[i][u];
    if(u==v)return u;
    for(int i=logn-1;i>=0;i--)if(anc[i][u]!=anc[i][v])u=anc[i][u],v=anc[i][v];
    return anc[0][u];
}
int dis(int u,int v)
{
    int l=lca(u,v);
    return deep[u]+deep[v]-2*deep[l];
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n,q;
    cin>>n>>q;
    for(int i=2;i<=n;i++)
    {
        int a;
        cin>>a;
        g[a].push_back(i);
        g[i].push_back(a);
    } 
    for(int i=0;i<logn;i++)anc[i][1]=1;
    dfs(0,1);
    while(q--)
    {
        int a,b,c;
        cin>>a>>b>>c;
        int d1=(dis(a,b)+dis(b,c)-dis(a,c))/2+1;
        int d2=(dis(a,c)+dis(b,c)-dis(a,b))/2+1;
        int d3=(dis(a,b)+dis(a,c)-dis(b,c))/2+1;
        int ans=max(d1,max(d2,d3));
        cout<<ans<<endl;
    }
    return 0;
}

 

以上是关于Codeforces 832D - Misha, Grisha and Underground的主要内容,如果未能解决你的问题,请参考以下文章

Codeforces Round #425 (Div. 2) Problem D Misha, Grisha and Underground (Codeforces 832D) - 树链剖分 - 树状

[CF832D] Misha, Grisha and Underground

Codeforces 832 D Misha, Grisha and Underground

Codeforces 501C Misha and Forest(bfs)

CodeForces 501B Misha and Changing Handles(STL map)

CodeForces - 501B Misha and Changing Handles