Advertisement
ivnikkk

Untitled

May 22nd, 2022 (edited)
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.23 KB | None | 0 0
  1. #define _CRT_SECURE_NO_WARNINGS
  2. #define debug(l) cerr<<#l<<' '<<l<<'\n';
  3. #include "bits/stdc++.h"
  4. using namespace std;
  5. #define all(a) a.begin(), a.end()
  6. typedef long long ll;
  7. typedef pair<ll, ll> pll;
  8. typedef pair<int, int> pii;
  9. typedef long double ld;
  10. struct Node {
  11.     unordered_map<int, int> clrs; // кол во вершин с цветом key
  12.     unordered_map<int, int> cnt; // кол во цветов которые имеют i вершин в поддереве
  13. };
  14. vector<vector<int>> gr;
  15. vector<int> color;
  16. vector<Node> sub;
  17. struct query {
  18.     int k, ind;
  19. };
  20. vector<vector<query>> q;
  21. vector<int> ans;
  22. void dfs(int v, int p) {
  23.     sub[v].clrs[color[v]]++;
  24.     sub[v].cnt[1]++;
  25.     for (int& u : gr[v]) {
  26.         if (u != p) {
  27.             dfs(u, v);
  28.             if (sub[v].clrs.size() < sub[u].clrs.size())sub[v].clrs.swap(sub[u].clrs),sub[v].cnt.swap(sub[u].cnt);
  29.             for (auto& i : sub[u].clrs) {
  30.                 if (sub[v].clrs.find(i.first) != sub[v].clrs.end()) {
  31.                     sub[v].cnt[sub[v].clrs[i.first]]--;
  32.                 }
  33.                 sub[v].clrs[i.first] += i.second;
  34.                 sub[v].cnt[sub[v].clrs[i.first]]++;
  35.             }
  36.             sub[u].clrs.clear();
  37.             sub[u].cnt.clear();
  38.         }
  39.     }
  40.     for (query& i : q[v]) {
  41.         int res = 0;
  42.         for (auto& it : sub[v].cnt) {
  43.             if (it.first >= i.k) {
  44.                 res += it.second;
  45.             }
  46.         }
  47.         ans[i.ind] = res;
  48.     }
  49. }
  50. signed main() {
  51. #ifdef _DEBUG
  52.     freopen("input.txt", "r", stdin);
  53.     freopen("output.txt", "w", stdout);
  54. #endif
  55.     ios_base::sync_with_stdio(false);
  56.     cin.tie(nullptr);
  57.     cout.tie(nullptr);
  58.     int n, m;
  59.     cin >> n >> m;
  60.     color.resize(n), gr.resize(n), sub.resize(n), q.resize(n), ans.resize(m);
  61.     for (int i = 0; i < n; i++) {
  62.         cin >> color[i];
  63.     }
  64.     for (int i = 0; i < n - 1; i++) {
  65.         int u, v;
  66.         cin >> u >> v;
  67.         u--, v--;
  68.         gr[v].push_back(u);
  69.         gr[u].push_back(v);
  70.     }
  71.     for (int i = 0; i < m; i++){
  72.         int v, k;
  73.         cin >> v >> k;
  74.         v--;
  75.         q[v].push_back({ k,i });
  76.     }
  77.     dfs(0, -1);
  78.     for (int& i : ans) {
  79.         cout << i << '\n';
  80.     }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement