Problem - L - Codeforces
题意:
思路:
Code:
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int mxn=1e6+10;
const int mxe=1e6+10;
vector<int> G[mxn],lp;
int N,Fa;
int son[mxn],len[mxn];
void dfs1(int u,int fa){
for(auto v:G[u]){
if(v==fa) continue;
dfs1(v,u);
if(len[v]>len[son[u]]) son[u]=v;
}
len[u]=len[son[u]]+1;
}
void dfs2(int u,int dep,int fa){
if(!son[u]){
lp.push_back(dep);
}else{
dfs2(son[u],dep+1,u);
for(auto v:G[u]){
if(v==fa) continue;
if(v!=son[u]){
dfs2(v,1,u);
}
}
}
}
void solve(){
cin>>N;
lp.clear();
for(int i=1;i<=N;i++){
G[i].clear();
len[i]=0;
son[i]=0;
}
for(int i=2;i<=N;i++){
cin>>Fa;
G[Fa].push_back(i);
G[i].push_back(Fa);
}
dfs1(1,0);
dfs2(1,1,0);
sort(lp.begin(),lp.end(),greater<int>());
int ans=lp.size();
for(int i=0;i<lp.size();i++){
ans=min(ans,lp[i]+i);
}
cout<<ans<<'\n';
}
signed main(){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int __=1;cin>>__;
while(__--)solve();return 0;
}