当前位置:网站首页>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;
}
边栏推荐
- [interval problem] 435 Non overlapping interval
- Romance of programmers on Valentine's Day
- Educational Codeforces Round 107 (Rated for Div. 2) E. Colorings and Dominoes
- 质量体系建设之路的分分合合
- Haut OJ 1221: a tired day
- Sword finger offer 05 Replace spaces
- 剑指 Offer 53 - II. 0~n-1中缺失的数字
- Mysql database (I)
- Daily question - Search two-dimensional matrix PS two-dimensional array search
- A new micro ORM open source framework
猜你喜欢
质量体系建设之路的分分合合
Sword finger offer 35 Replication of complex linked list
Pointnet++ learning
Sword finger offer 05 Replace spaces
Web APIs DOM节点
National teacher qualification examination in the first half of 2022
一个新的微型ORM开源框架
On-off and on-off of quality system construction
Remote upgrade afraid of cutting beard? Explain FOTA safety upgrade in detail
浅谈JVM(面试常考)
随机推荐
A misunderstanding about the console window
Daily question - longest substring without repeated characters
Time complexity and space complexity
读者写者模型
After setting up the database and website When you open the app for testing, it shows that the server is being maintained
Acwing 4301. Truncated sequence
Haut OJ 1243: simple mathematical problems
Sword finger offer 53 - ii Missing numbers from 0 to n-1
动漫评分数据分析与可视化 与 IT行业招聘数据分析与可视化
What is the agile proportion of PMP Exam? Dispel doubts
Download xftp7 and xshell7 (official website)
Mysql database (I)
对象的序列化
Support multi-mode polymorphic gbase 8C database continuous innovation and heavy upgrade
object serialization
Reader writer model
用STM32点个灯
SAP-修改系统表数据的方法
常见的最优化方法
浅谈JVM(面试常考)