Codeforces 246E Blood Cousins Return(树上启发式合并)

时间:2022-04-02 15:31:25

题目链接 Blood Cousins Return

 #include <bits/stdc++.h>

 using namespace std;

 #define rep(i, a, b) for (int i(a); i <= (b); ++i)

 const int N = ;

 string s[N];
int ans[N], sz[N], h[N];
bool skip[N];
vector <int> v[N];
vector < pair<int, int> > query[N];
int n, m, x, y, q; unordered_map <string, int> mp[N]; void getsz(int x){
sz[x] = ;
for (auto u : v[x])
h[u] = h[x] + , getsz(u), sz[x] += sz[u];
} void del(int x){
auto it = mp[h[x]].find(s[x]);
--it->second;
if (!it->second) mp[h[x]].erase(it);
for (auto u : v[x]) if (!skip[u]) del(u);
} void add(int x){
mp[h[x]][s[x]]++;
for (auto u : v[x]) if (!skip[u]) add(u);
} void dfs(int x, bool keep = ){
int mx = , p = ;
for (auto u : v[x]) if (mx < sz[u]){ mx = sz[u]; p = u;}
for (auto u : v[x]) if (u != p) dfs(u, );
if (p) dfs(p), skip[p] = ; add(x);
for (auto q: query[x])
ans[q.second] = mp[h[x] + q.first].size(); if (p) skip[p] = ;
if (keep) del(x);
} int main(){ scanf("%d", &n);
rep(i, , n){
cin >> s[i] >> x;
v[x].push_back(i);
} scanf("%d", &q);
rep(i, , q){
scanf("%d%d", &x, &y);
query[x].push_back({y, i});
} getsz();
dfs(); rep(i, , q) printf("%d\n", ans[i]);
return ;
}