#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int mxN = 2e5+10;
const int mxR = 25010;
int reg[mxN];
vector<int> adj[mxN], emp[mxR];
int tin[mxN], tout[mxN], timer = 0;
int idx[mxR], cntr = 0;
int precalc[500][mxR], tin_idx[mxN];
void dfs(int node, int p) {
tin[node] = timer++;
tin_idx[timer-1] = node;
emp[reg[node]].push_back(tin[node]);
for(auto it : adj[node]) {
if(it == p) continue;
dfs(it, node);
}
tout[node] = timer;
}
void dfs1(int node, int p, int cnt, int region) {
if(reg[node] != region) precalc[idx[region]][reg[node]] += cnt;
for(auto it : adj[node]) {
if(it == p) continue;
dfs1(it, node, cnt+(reg[node] == region), region);
}
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, r, q;
cin >> n >> r >> q;
cin >> reg[1];
for(int i = 2; i <= n; i++) {
int p;
cin >> p >> reg[i];
adj[p].push_back(i);
adj[i].push_back(p);
}
dfs(1, 0);
for(int i = 1; i <= r; i++) {
if(emp[i].size() > 500) {
idx[i] = cntr++;
dfs1(1, 0, 0, i);
}
}
while(q--) {
int r1, r2;
cin >> r1 >> r2;
if(emp[r1].size() <= 500) {
int ans = 0;
for(auto it1 : emp[r1]) {
int it = tin_idx[it1];
int now = lower_bound(emp[r2].begin(), emp[r2].end(), tout[it]) -
lower_bound(emp[r2].begin(), emp[r2].end(), tin[it]);
ans += now;
}
}
else {
cout << precalc[idx[r1]][r2] << '\n';
}
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |