2020杭电多校第九场 Tree

第一题: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;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值