Advertisement
Dmaxiya

颜色平衡树 参考代码

Apr 4th, 2025
349
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.17 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. typedef long long LL;
  5. const int maxn = 200000 + 100;
  6. int n, f, ans;
  7. int c[maxn], id[maxn], son[maxn], mxCnt[maxn];
  8. vector<int> G[maxn];
  9. map<int, int> cnt[maxn];
  10. map<int, int>::iterator it;
  11.  
  12. int merge(int id1, int id2) {
  13.     if (cnt[id1].size() > cnt[id2].size()) {
  14.         swap(id1, id2);
  15.     }
  16.     for (it = cnt[id1].begin(); it != cnt[id1].end(); ++it) {
  17.         cnt[id2][it->first] += it->second;
  18.         mxCnt[id2] = max(mxCnt[id2], cnt[id2][it->first]);
  19.     }
  20.     return id2;
  21. }
  22.  
  23. void dfs(int root) {
  24.     int &idd = id[root];
  25.     cnt[idd][c[root]] = 1;
  26.     for (int pos : G[root]) {
  27.         dfs(pos);
  28.         idd = merge(idd, id[pos]);
  29.         son[root] += son[pos];
  30.     }
  31.     if ((LL) mxCnt[idd] * cnt[idd].size() == son[root]) {
  32.         ++ans;
  33.     }
  34. }
  35.  
  36. int main() {
  37. #ifdef ExRoc
  38.     freopen("test.txt", "r", stdin);
  39. #endif // ExRoc
  40.     ios::sync_with_stdio(false);
  41.  
  42.     cin >> n;
  43.     for (int i = 1; i <= n; ++i) {
  44.         cin >> c[i] >> f;
  45.         G[f].push_back(i);
  46.         id[i] = i;
  47.         mxCnt[i] = 1;
  48.         son[i] = 1;
  49.     }
  50.     dfs(1);
  51.     cout << ans << endl;
  52.  
  53.     return 0;
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement