2017 Multi-University Training Contest - Team 1 1003 Colorful Tree

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6035


题目大意: 给一棵n个点树, 每一个点有一个颜色ci, 对于每一条边对答案的贡献为这一条边上颜色不同的个数, 问有的n * (n - 1) / 2条边的贡献和是多小。

参考博客:http://blog.csdn.net/my_sunshine26/article/details/76163937

解题思路: 首先可以想如果每一个点对于每一条边都有贡献, 那么总答案为n * n * (n - 1) / 2, 但是有一些颜色对于一些边来说是没有贡献的, 那么我们就要考虑如何减去。

  我们用num[i]表示以i为“根节点”,其子树的节点个数和(包括自身,且整棵树的根节点,即1,事先已经确定)。

再用sum[color[u]]表示搜索到u点时,以其为根节点的每棵子树中距离u最近且颜色相等的节点x的num[x]值的和。

容易知道,每搜索一次u的根节点v,sum[color[u]]的值会变大temp,且num[v]-temp的值即表示这些点之间的路径不经过color[u]这种颜色,这种路径的数量为temp*(temp-1)/2,应减去,重复此操作即可。




#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<vector>
#include<algorithm>
using namespace std;
const int MaxN = 2e6;
typedef long long LL;

LL ans, n;  
LL num[MaxN + 5], sum[MaxN + 5];
int color[MaxN + 5];
vector<int> edge[MaxN + 5];

void dfs(int u, int fa){
	int add = 0;
	num[u] = 1;
	for(int i = 0; i < edge[u].size(); i++){
		int v = edge[u][i];
		if(v == fa) continue;
		int pre = sum[color[u]];
		dfs(v, u);
		num[u] += num[v];
		int temp = num[v] - (sum[color[u]] - pre);
		ans -= (LL)temp *(temp - 1) / 2;
		add += temp;
	}
	sum[color[u]] += add + 1;
}

int main(){
	int Case = 0;
	while(~scanf("%lld", &n)){
		memset(num, 0, sizeof(num));
		memset(sum, 0, sizeof(sum));
		for(int i = 1; i <= n; i++) edge[i].clear();
		ans = 0;
		for(int i = 1; i <= n; i++) scanf("%d", &color[i]);
		for(int i = 1; i < n; i++){
			int u, v;
			scanf("%d %d", &u, &v);
			edge[u].push_back(v);
			edge[v].push_back(u);
		}
		ans = n * n * (n - 1LL) / 2LL;
		dfs(1, -1);
		for(int i = 1;i <= n;i++){
            int temp = n - sum[i];  
            ans -= (LL)temp * (temp - 1) / 2;  
        } 
        printf("Case #%d: %lld\n",++Case,ans);  
	}
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值