思路:在线LCA,分类讨论。题解做法:
# include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5+3;
vector<int>v[maxn];
int h[maxn], fa[maxn][20];
void dfs(int cur, int pre)
{
fa[cur][0] = pre;
for(int i=1; i<20; ++i)
fa[cur][i] = fa[fa[cur][i-1]][i-1];
for(auto to : v[cur])
{
if(to == pre) continue;
h[to] = h[cur] + 1;
dfs(to, cur);
}
}
int lca(int v, int u)
{
if(h[v] > h[u]) swap(v, u);
for(int i=0; i<20; ++i)
if(h[u]-h[v]>>i & 1)
u = fa[u][i];
for(int i=19; i>=0; --i)
if(fa[v][i] != fa[u][i])
v = fa[v][i], u=fa[u][i];
return v == u?v:fa[v][0];
}
int cal(int s, int t, int f)
{
int ans=0, sf = lca(s, f)==f, tf = lca(t, f)==f;
if(sf != tf) return 1;//一个lca为f一个不是,返回1.
else if(sf) ans = h[lca(s, t)] - h[f];//两个都是。
else if(lca(s, f) != lca(t, f)) ans = h[f] - max(h[lca(f,s)], h[lca(f, t)]);//(s,e在不同支,f在他们其中一支)。
else ans = h[lca(s, t)] + h[f] - 2*h[lca(s, f)];//(s,e在同一支,f在另一支)
return ans + 1;
}
int main()
{
int n, q;
scanf("%d%d",&n,&q);
for(int i=2; i<=n; ++i)
{
int x;
scanf("%d",&x);
v[i].push_back(x);
v[x].push_back(i);
}
dfs(1, 0);
while(q--)
{
int a, b, c;
scanf("%d%d%d",&a,&b,&c);
printf("%d\n",max(cal(a, b, c), max(cal(b, c, a), cal(c, a, b))));
}
return 0;
}