当前位置:网站首页>2020ccpc Qinhuangdao J - Kingdom's power

2020ccpc Qinhuangdao J - Kingdom's power

2022-07-05 05:31:00 solemntee

#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;
}

原网站

版权声明
本文为[solemntee]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140621453104.html