#include<bits/stdc++.h>
using namespace std;
vector<int>v[1000005];
int siz[1000005],dep[1000005];
int dp[2][1000005];
void dfs1(int x,int pre)
{
siz[x]=1;
if(x!=1)dep[x]=dep[pre]+1;
for(auto to:v[x])if(to!=pre)
{
dfs1(to,x);
siz[x]+=siz[to];
}
}
void dfs(int x,int pre)
{
dp[0][x]=siz[x]*2;
if((int)v[x].size()==1&&x!=1)
{
dp[1][x]=dep[x];
return;
}
bool flag=false;
int ans=0;
int mn=1000000;
for(auto to:v[x])if(to!=pre)
{
dfs(to,x);
if(dp[1][to]<=dp[0][to])
{
flag=true;
ans+=dp[1][to];
mn=min(mn,dp[1][to]-dp[0][to]);
}
else
{
ans+=dp[0][to];
mn=min(mn,dp[1][to]-dp[0][to]);
}
}
if(flag==false)ans+=mn;
dp[1][x]=ans;
}
int main()
{
int T;
scanf("%d",&T);
for(int tt=1;tt<=T;tt++)
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)v[i].clear();
for(int i=1;i<=n;i++)dp[1][i]=dp[0][i]=0;
for(int i=1;i<n;i++)
{
int temp;
scanf("%d",&temp);
v[i+1].push_back(temp);
v[temp].push_back(i+1);
}
dfs1(1,1);
dfs(1,1);
printf("Case #%d: %d\n",tt,dp[1][1]);
}
return 0;
}
2020CCPC秦皇岛 J - Kingdom‘s Power
最新推荐文章于 2024-09-09 22:12:12 发布