https://vjudge.net/contest/402960#problem/J
Alex is a professional computer game player.
These days, Alex is playing a war strategy game. The kingdoms in the world form a rooted tree. Alex's kingdom 11 is the root of the tree. With his great diplomacy and leadership, his kingdom becomes the greatest empire in the world. Now, it's time to conquer the world!
Alex has almost infinite armies, and all of them are located at 11 initially. Every week, he can command one of his armies to move one step to an adjacent kingdom. If an army reaches a kingdom, that kingdom will be captured by Alex instantly.
Alex would like to capture all the kingdoms as soon as possible. Can you help him?
Input
The first line of the input gives the number of test cases, T (1≤T≤105)T (1≤T≤105). TT test cases follow.
For each test case, the first line contains an integer n (1≤n≤106)n (1≤n≤106), where nn is the number of kingdoms in the world.
The next line contains (n−1)(n−1) integers f2,f3,⋯,fn (1≤fi<i)f2,f3,⋯,fn (1≤fi<i), representing there is a road between fifi and ii.
The sum of nn in all test cases doesn't exceed 5×1065×106.
Output
For each test case, output one line containing "Case #x: y", where xx is the test case number (starting from 11), and yy is the minimum time to conquer the world.
Example
Input
2 3 1 1 6 1 2 3 4 4
Output
Case #1: 2 Case #2: 6
Sponsor
#include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <set>
#include<unordered_map>
using namespace std;
typedef long long ll;
const ll maxn=1e6+10,inf=1<<29;
ll mod=1e9+7;
ll t,n,m,ans,s;
ll vis[maxn],dis[maxn];
ll f[maxn];
ll dp[maxn];
int main()
{
cin>>t;
for(int o=1;o<=t;o++)
{
scanf("%lld",&n);
for(int i=2;i<=n;i++)
{
scanf("%lld",&f[i]);
dp[i]=0;
dis[i]=0;
}
dp[1]=0;
dis[1]=0;
for(int i=2;i<=n;i++)
{
dis[i]=dis[f[i]]+1;
}
ans=0;
for(int i=n;i>=2;i--)
{
if(dp[f[i]]<dp[i]+1)
{
ans+=dp[f[i]]+min(dp[f[i]],dis[f[i]]);
dp[f[i]]=dp[i]+1;
}
else
{
if(dp[f[i]]==0)
{
dp[f[i]]=dp[i]+1;
}
else
{
ans+=dp[i]+1+min(dp[i]+1,dis[f[i]]);
}
}
}
ans+=dp[1];
printf("Case #%d: ",o);
printf("%lld\n",ans);
}
return 0;
}

Alex是一名职业电脑游戏玩家,他正在玩一个战争策略游戏。游戏中的王国形成了一个根为1的树形结构。通过出色的外交和领导力,他的王国1成为了世界最强大的帝国。现在,他准备征服全世界!Alex拥有几乎无限的军队,且全部位于王国1。每周,他可以指挥一支军队向相邻的王国移动一步。如果一支军队到达一个王国,该王国会被立即占领。目标是帮助Alex尽快征服所有王国。
2744

被折叠的 条评论
为什么被折叠?



