第一题:Tree
题目:
You are given a tree consisting of n vertices numbered 1 to n rooted at node 1. The parent of the i-th vertices is pi. You can move from a vertex to any of its children. What’s more, you can add one directed edge between any two different vertices, and you can move through this edge too. You need to maximize the number of pairs (x,y) such that x can move to y through the edges after adding the edge. Note that x can also move to x.
思路
最优解一定是某个叶子结点连向根节点,那么这条路径上的点给予的权值就会变成n,直接dfs一遍求出所有答案取最大值即可。
代码
#include<iostream>
#include<vector>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef unsigned long long ull;
const int N=5e5+7;
ll ans,s;
int f[N];
ll a[N],d[N];
vector<ll> ve[N];
int n;
void dfs(int u)
{
a[u]=1;
d[u]=d[f[u]]+1;
for(int v : ve[u])
{
dfs(v);
a[u]+=a[v];
}
s+=a[u];
}
void dfs1(int u,ll x)
{
ans=max(ans,x);
for(int v : ve[u])
{
dfs1(v,x+n-a[v]);
}
}
int main()
{
int T;
cin>>T;
while(T--)
{
scanf("%d",&n);
s=ans=0;
//memset(a,0,sizeof a);
//memset(d,0,sizeof d);
for(int i=2;i<=n;i++)
{
scanf("%d",&f[i]);
ve[f[i]].push_back(i);
}
dfs(1);
dfs1(1,s);
for(int i=1;i<=n;i++)
ve[i].clear();
cout<<ans<<endl;
}
return 0;
}