const double eps = 1e-6; const LL mod=1e9+7; const LL INF=(LL)1e18; using namespace std; LL gcd(LL a,LL b){return b==0?a:gcd(b,a%b);} LL qpow(LL x,LL y){LL re=1,base=x%mod;while(y){if(y&1)re=(re*base)%mod;base=(base*base)%mod;y>>=1;}return re;} int vis[maxn],deep[maxn],f[maxn],anc[maxn][25]; int dis[maxn]; vector<int>e[maxn]; void dfs(int x,int fa){ anc[x][0]=f[x]; for(int i=1;i<=20;i++) anc[x][i]=anc[anc[x][i-1]][i-1]; for(int i=0;i<e[x].size();i++){ int next=e[x][i]; if(next!=fa){ f[next]=x; deep[next]=deep[x]+1; dfs(next,x); } } } int lca(int x,int y){ if(deep[x]<deep[y]) swap(x,y); for(int i=20;i>=0;i--) if(deep[anc[x][i]]>=deep[y]) x=anc[x][i]; if(x==y) return x; for(int i=20;i>=0;i--) if(anc[x][i]!=anc[y][i]) x=anc[x][i],y=anc[y][i]; return f[x]; } void dfs2(int id){ for(int i=0;i<e[id].size();i++){ int next=e[id][i]; if(vis[next]) continue; dis[next]=dis[id]+1; vis[next]=1; dfs2(next); } } int solve(int f,int s,int t){ int l1=lca(f,s); int len1=dis[s]+dis[f]-2*dis[l1]; int l2=lca(f,t); int len2=dis[f]+dis[t]-2*dis[l2]; int l3=lca(s,t); int len3=dis[s]+dis[t]-2*dis[l3]; return (len1+len2-len3)/2+1; } int main(){ // freopen("input.txt","r",stdin); // freopen("ouput.txt","w",sdout); ios::sync_with_stdio(false); cin.tie(0),cout.tie(0); int n,q; cin>>n>>q; for(int i=2;i<=n;i++){ int x; cin>>x; e[x].pb(i); e[i].pb(x); } mm(vis,0),mm(f,0),mm(anc,0),mm(deep,0),mm(dis,0); deep[1]=1; dfs(1,0); vis[1]=1; dfs2(1); while(q--){ int a,b,c; cin>>a>>b>>c; int ans=0; ans=max(ans,solve(a,b,c)); ans=max(ans,solve(b,a,c)); ans=max(ans,solve(c,b,a)); cout<<ans<<endl; } return 0; }
|