CSU 1811 Tree Intersection(启发式合并)
来源:互联网 发布:php usleep函数 编辑:程序博客网 时间:2024/05/22 15:31
思路:对于某一颗子树来说,只需要统计这颗子树拥有的颜色和这颗子树独有的颜色,两者一减就是答案,考虑一直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
41 2 2 11 22 33 451 1 2 1 21 32 33 54 5
Sample Output
1211121
Hint
0 0
- CSU 1811 Tree Intersection(启发式合并)
- CSU 1811 Tree Intersection(启发式合并)
- CSU 1811 Tree Intersection(线段树+启发式合并 解法)
- CSU 1811 Tree Intersection(Treap启发式合并)
- CSU 1811 Tree Intersection 平衡树启发式合并
- [CSU - 1811 (湖南省赛16)] Tree Intersection (启发式合并)
- CSU 1811 Tree Intersection
- CSU 1811 Tree Intersection
- CSU 1811 Tree Intersection(莫队算法)
- CSU 1811 Tree Intersection(dfs序+莫队算法)
- csu 1811 Tree Intersection 2016湖南省赛 I
- poj1741:Tree (树上点分治/treap+启发式合并)
- HDU6191Query on A Tree(字典树启发式合并)
- [CSU - 1811 (湖南省赛16)] Tree Intersection (dfs序维护子树+离线询问+树状数组)
- csu1811 Tree Intersection(线段树合并)★ ★ ★
- BZOJ 2212([Poi2011]Tree Rotations-启发式合并)
- hdu4812 D Tree,平衡树,启发式合并
- poj1741 Tree,平衡树,启发式合并
- Java动态代理
- 【JAVA学习笔记】随机数
- 【OpenGL】OpenGL颜色立方体
- 项目开发管理
- SQL应用之根据数据库表生成Extjs的model
- CSU 1811 Tree Intersection(启发式合并)
- SPFA算法模板
- 抽象类
- 二进制中1的个数
- 单例
- js--严格模式 'use strict'
- [LeetCode]289. Game of Life
- 求两个数的最大公约数的四种方法
- 求最小公倍数和最大公约数