Codeforces 832D - Misha, Grisha and Underground

时间:2022-02-24 03:25:25

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+;
const int logn=;
vector<int>g[N];
int anc[logn][N];
int deep[N];
void dfs(int o,int u)
{
deep[u]=deep[o]+;
for(int j=;j<g[u].size();j++)
{
if(g[u][j]!=o)
{
anc[][g[u][j]]=u;
for(int i=;i<logn;i++)anc[i][g[u][j]]=anc[i-][anc[i-][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-;i>=;i--)if(deep[anc[i][u]]>=deep[v])u=anc[i][u];
if(u==v)return u;
for(int i=logn-;i>=;i--)if(anc[i][u]!=anc[i][v])u=anc[i][u],v=anc[i][v];
return anc[][u];
}
int dis(int u,int v)
{
int l=lca(u,v);
return deep[u]+deep[v]-*deep[l];
}
int main()
{
ios::sync_with_stdio(false);
cin.tie();
int n,q;
cin>>n>>q;
for(int i=;i<=n;i++)
{
int a;
cin>>a;
g[a].push_back(i);
g[i].push_back(a);
}
for(int i=;i<logn;i++)anc[i][]=;
dfs(,);
while(q--)
{
int a,b,c;
cin>>a>>b>>c;
int d1=(dis(a,b)+dis(b,c)-dis(a,c))/+;
int d2=(dis(a,c)+dis(b,c)-dis(a,b))/+;
int d3=(dis(a,b)+dis(a,c)-dis(b,c))/+;
int ans=max(d1,max(d2,d3));
cout<<ans<<endl;
}
return ;
}