题目链接:https://codeforces.com/problemset/problem/600/E
这是一道树上启发式合并的题,就只是在模板的基础上稍微变化了一下
解题思路:我们需要计算当前u节点的答案,要计算加入非重链节点对此答案的影响,在计算加入节点对ans影响的时候,遍历u除了重链外的所有子树节点(因为重链部分的颜色已经被记录在了cnt内),当目前颜色数量(cnt[col[x]])大于记录的最大颜色数,就更新一下最大颜色数和sum颜色编号和,如果等于最大颜色数那么就让sum加等于这个颜色编号。
AC代码:
1 #include<iostream> 2 #include<algorithm> 3 #include<cstring> 4 #include<cmath> 5 #include<vector> 6 #include<set> 7 #include<queue> 8 #define int long long 9 #define el "\n" 10 #define inf 0x3f3f3f3f 11 using namespace std; 12 using ll = long long; 13 const int N = 100005; 14 const int mod = 9901; 15 16 int col[N]; 17 18 vector<int> G[N]; 19 20 int dfn[N], ctr[N], tot, siz[N], rnk[N], son[N]; 21 int cnt[N], sum, mx, ans[N]; 22 23 void add(int x) { 24 cnt[col[x]] ++; 25 if (cnt[col[x]] > mx) { 26 mx = cnt[col[x]]; 27 sum = col[x]; 28 } 29 else if (cnt[col[x]] == mx) sum += col[x]; 30 } 31 32 void del(int x) { 33 cnt[col[x]] --; 34 } 35 36 int getans() { 37 return sum; 38 } 39 40 void dfs1(int u, int p) { 41 dfn[u] = ++tot; 42 siz[u] = 1; 43 rnk[tot] = u; 44 for (auto v :G[u]) { 45 if (v != p) { 46 dfs1(v, u); 47 siz[u] += siz[v]; 48 if (siz[son[u]] < siz[v]) son[u] = v; 49 } 50 } 51 ctr[u] = tot; 52 } 53 54 void dfs2(int u, int p, bool keep) { 55 for (auto v :G[u]) { 56 if (v != p && v != son[u]) { 57 dfs2(v, u, false); 58 } 59 } 60 if (son[u]) dfs2(son[u], u, true); 61 for (auto v :G[u]) { 62 if (v != p && v != son[u]) { 63 for (int i = dfn[v]; i <= ctr[v]; i++) { 64 add(rnk[i]); 65 } 66 } 67 } 68 add(u); 69 ans[u] = getans(); 70 if (!keep) { 71 for (int i = dfn[u]; i <= ctr[u]; i++) { 72 del(rnk[i]); 73 } 74 sum = mx = 0; 75 } 76 } 77 78 79 signed main() { 80 81 ios::sync_with_stdio(false); 82 cin.tie(0), cout.tie(0); 83 int n; 84 cin >> n; 85 for (int i = 1; i <= n; i++) { 86 cin >> col[i]; 87 } 88 for (int i = 1; i < n; i++) { 89 int u, v; 90 cin >> u >> v; 91 G[u].push_back(v); 92 G[v].push_back(u); 93 } 94 dfs1(1, 0); 95 dfs2(1, 0, 1); 96 for (int i = 1; i <= n; i++) cout << ans[i] << " "; 97 98 return 0; 99 }
标签:cnt,int,sum,son,gelral,CF600E,include,col,Lomsat From: https://www.cnblogs.com/wabi/p/17364293.html