// IamHereForFun //
#include <bits/stdc++.h>
using namespace std;
#define LSOne(X) ((X) & -(X))
const int N = 2e5 + 5;
const int M = 1e2 + 5;
const int C = 26;
const int LG = 20;
const int R = 25e3 + 5;
const int B = 450;
const int INF = 1e9 + 5;
const int MOD = 1e9 + 7;
int n, r, q, home[N], cnt_home[N], heavy[B][R], in[N], out[N], cid = 0, heavy_idx[R];
vector<pair<int, int>> range[R];
vector<int> adj[N];
void dfs1(int c)
{
in[c] = cid++;
for(int i : adj[c])
{
dfs1(i);
}
out[c] = cid++;
// cout << home[c] << "\n";
range[home[c]].push_back({in[c], out[c]});
}
void dfs2(int c, int t, int cnt)
{
if(home[c] == t) cnt++;
heavy[heavy_idx[t]][home[c]] += cnt;
for(int i : adj[c])
{
dfs2(i, t, cnt);
}
}
void solve()
{
cin >> n >> r >> q;
cin >> home[1];
cnt_home[home[1]]++;
for(int x = 2; x <= n; x++)
{
int i; cin >> i;
adj[i].push_back(x);
cin >> home[x];
cnt_home[home[x]]++;
}
dfs1(1);
cid = 0;
for(int x = 1; x <= r; x++)
{
if(cnt_home[x] >= B)
{
heavy_idx[x] = cid++;
dfs2(1, x, 0);
}
}
for(int x = 1; x <= r; x++) sort(range[x].begin(), range[x].end());
for(int x = 0; x < q; x++)
{
int r1, r2; cin >> r1 >> r2;
if(cnt_home[r1] >= B)
{
cout << heavy[heavy_idx[r1]][r2] << endl;
}
else
{
int ans = 0;
for(pair<int, int> p : range[r1])
{
ans += lower_bound(range[r2].begin(), range[r2].end(), make_pair(p.second, 0)) - lower_bound(range[r2].begin(), range[r2].end(), make_pair(p.first, 0));
}
cout << ans << endl;
}
}
}
signed main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t = 1;
// cin >> t;
for (int x = 1; x <= t; x++)
{
solve();
}
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |