2020杭电多校第九场 Tree

   日期:2020-08-20     浏览:92    评论:0    
核心提示:第一题: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 vert

第一题: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;
}
 
打赏
 本文转载自:网络 
所有权利归属于原作者,如文章来源标示错误或侵犯了您的权利请联系微信13520258486
更多>最近资讯中心
更多>最新资讯中心
0相关评论

推荐图文
推荐资讯中心
点击排行
最新信息
新手指南
采购商服务
供应商服务
交易安全
关注我们
手机网站:
新浪微博:
微信关注:

13520258486

周一至周五 9:00-18:00
(其他时间联系在线客服)

24小时在线客服