当前位置:网站首页>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;
}
边栏推荐
猜你喜欢

Pointnet++的改进

Corridor and bridge distribution (csp-s-2021-t1) popular problem solution

YOLOv5添加注意力机制
![[depth first search] 695 Maximum area of the island](/img/08/cfff4aec667216e4f146205a12c13f.jpg)
[depth first search] 695 Maximum area of the island

剑指 Offer 58 - II. 左旋转字符串
![[to be continued] [UE4 notes] L2 interface introduction](/img/0f/268c852b691bd7459785537f201a41.jpg)
[to be continued] [UE4 notes] L2 interface introduction

Support multi-mode polymorphic gbase 8C database continuous innovation and heavy upgrade

剑指 Offer 53 - II. 0~n-1中缺失的数字

Binary search basis
![[to be continued] [depth first search] 547 Number of provinces](/img/c4/b4ee3d936776dafc15ac275d2059cd.jpg)
[to be continued] [depth first search] 547 Number of provinces
随机推荐
游戏商城毕业设计
High precision subtraction
Maximum number of "balloons"
Sword finger offer 53 - I. find the number I in the sorted array
常见的最优化方法
剑指 Offer 35.复杂链表的复制
Romance of programmers on Valentine's Day
MySQL数据库(一)
Find a good teaching video for Solon framework test (Solon, lightweight application development framework)
[turn to] MySQL operation practice (III): table connection
剑指 Offer 58 - II. 左旋转字符串
Warning using room database: schema export directory is not provided to the annotation processor so we cannot export
质量体系建设之路的分分合合
On-off and on-off of quality system construction
[depth first search] 695 Maximum area of the island
Solon 框架如何方便获取每个请求的响应时间?
Chapter 6 data flow modeling - after class exercises
卷积神经网络简介
Csp-j-2020-excellent split multiple solutions
Talking about JVM (frequent interview)