CSU 1811 Tree Intersection(启发式合并)

本文介绍了一种使用树形动态规划的方法来解决求树上边删除后两部分节点颜色交集大小的问题。通过深度优先搜索(DFS)并采用自底向上的方式合并子树信息,最终达到O(n log n)的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:对于某一颗子树来说,只需要统计这颗子树拥有的颜色和这颗子树独有的颜色,两者一减就是答案,考虑一直DFS到子树,然后向上合并,合并的时候将结点数小的往大的合并,这样可以做到nlogn的复杂度


#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5+7;
struct Edge
{
	int v,id;
	Edge(){};
	Edge(int vv,int idd):v(vv),id(idd){};
};
vector<Edge>e[maxn];
int n,c[maxn],sum[maxn],res[maxn],ans[maxn];
map<int,int>cnt[maxn];    //cnt[u][i] 结点u颜色i有多少个
void dfs(int u,int fa,int id)
{
    cnt[u][c[u]]=1;
	ans[u]=cnt[u][c[u]]<sum[c[u]]?1:0;
	for(int i = 0;i<e[u].size();i++)
	{
		int v = e[u][i].v;
		int id = e[u][i].id;
		if(v==fa)continue;
		dfs(v,u,id);
        if(cnt[u].size()<cnt[v].size())
		{
			swap(ans[u],ans[v]);
			swap(cnt[u],cnt[v]);
		}
		for(map<int,int>::iterator it = cnt[v].begin();it!=cnt[v].end();it++)
		{
			int &num = cnt[u][it->first];
			if(num==0 && num+it->second<sum[it->first])
				++ans[u];
            else if (num && num+it->second==sum[it->first])
				--ans[u];
			num+=it->second;
		}
	}
	res[id]=ans[u];
}
int main()
{
	while(scanf("%d",&n)!=EOF)
	{
		memset(sum,0,sizeof(sum));
		for(int i = 0;i<=n;i++)
			e[i].clear(),cnt[i].clear();
		for(int i = 1;i<=n;i++)
			scanf("%d",&c[i]),sum[c[i]]++;
		for(int i = 1;i<=n-1;i++)
		{
			int u,v;
			scanf("%d%d",&u,&v);
			e[u].push_back(Edge(v,i));
			e[v].push_back(Edge(u,i));
		}
		dfs(1,-1,0);
        for(int i = 1;i<=n-1;i++)
			printf("%d\n",res[i]);
	} 
}


Description

Bobo has a tree with n vertices numbered by 1,2,…,n and (n-1) edges. The i-th vertex has color c i, and the i-th edge connects vertices a iand b i.
Let C(x,y) denotes the set of colors in subtree rooted at vertex x deleting edge (x,y).
Bobo would like to know R_i which is the size of intersection of C(a i,b i) and C(b i,a i) for all 1≤i≤(n-1). (i.e. |C(a i,b i)∩C(b i,a i)|)

Input

The input contains at most 15 sets. For each set:
The first line contains an integer n (2≤n≤10 5).
The second line contains n integers c 1,c 2,…,c n (1≤c_i≤n).
The i-th of the last (n-1) lines contains 2 integers a i,b i (1≤a i,b i≤n).

Output

For each set, (n-1) integers R 1,R 2,…,R n-1.

Sample Input

4
1 2 2 1
1 2
2 3
3 4
5
1 1 2 1 2
1 3
2 3
3 5
4 5

Sample Output

1
2
1
1
1
2
1

Hint



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值