Title Link: http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1811
Give you a tree, each node has a color. Ask to delete an edge to form two subtrees trees, two subtrees trees have the same number of colors.
Heuristic merging, small merging into large. Similar topics have Http://codeforces.com/contest/600/problem/E.
1 //#pragma COMMENT (linker, "/stack:102400000, 102400000")2#include <algorithm>3#include <iostream>4#include <cstdlib>5#include <cstring>6#include <cstdio>7#include <vector>8#include <cmath>9#include <ctime>Ten#include <list> One#include <Set> A#include <map> - using namespacestd; -typedefLong LongLL; thetypedef pair <int,int>P; - Const intN = 1e5 +5; - structEdge { - intnext, to, index; +}edge[n <<1]; - intColor[n], head[n], tot; + intSum[n], Ans[n], res[n];//Sum[color]: Color number of nodes, Ans[u] represents the U-point and byte-point answer, Res[edge] represents the side of the answer AMap <int,int> Cnt[n];//Cnt[u][color] Represents the number of nodes in the U-Tree color Color at - voidInitintN) { - for(inti =1; I <= N; ++i) { -Head[i] =-1; -Sum[i] =0; - cnt[i].clear (); in } -tot =0; to } + -InlinevoidAdd_edge (intUintVintID) { theEdge[tot].next =Head[u]; *Edge[tot].to =v; $Edge[tot].index =ID;Panax NotoginsengHead[u] = tot++; - } the + voidDfsintUintPreintID) { ACnt[u][color[u]] =1; theAns[u] = Cnt[u][color[u]] < Sum[color[u]]?1:0; + for(inti = Head[u]; ~i; i =Edge[i].next) { - intv =edge[i].to; $ if(v = =pre) $ Continue; - Dfs (V, u, edge[i].index); - if(Cnt[u].size () <cnt[v].size ()) { the swap (Cnt[u], cnt[v]); - swap (Ans[u], ans[v]);Wuyi } the for(Auto It:cnt[v]) { - int&num =Cnt[u][it.first]; Wu if(num = =0&& num + It.second <Sum[it.first]) { -++Ans[u]; About}Else if(num + it.second = sum[it.first] && num) {//indicates that the number of It.first color nodes for this subtree is full $--Ans[u]; - } -num + =It.second; - } A } +Res[id] =Ans[u]; the } - $ intMain () the { the intN, u, v; the while(SCANF ("%d", &n)! =EOF) { the init (n); - for(inti =1; I <= N; ++i) { inscanf"%d", Color +i); the++Sum[color[i]]; the } About for(inti =1; I < n; ++i) { thescanf"%d%d", &u, &v); the Add_edge (U, V, i); the Add_edge (V, U, i); + } -Dfs1, -1,0); the for(inti =1; I < n; ++i) {Bayiprintf"%d\n", Res[i]); the } the } - return 0; -}
CSU OJ 1811:tree intersection (heuristic merge)