1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| #include <iostream> #include <vector> #include <map> #define maxn 200010 using namespace std;
int n, m, r, a[maxn], num[maxn];
struct Edge { int to, next; } e[maxn * 2]; int c1, head[maxn]; inline void add_edge(int u, int v) { e[c1].to = v; e[c1].next = head[u]; head[u] = c1++; }
int ans[maxn], Q[maxn]; map<pair<int, int>, int> mp;
vector<pair<int, int>> A[maxn], B[maxn]; int cnt[maxn]; void dfs1(int u, int fa) { for (auto [k, id] : A[a[u]]) ans[id] += cnt[k]; ++cnt[a[u]]; for (int i = head[u]; ~i; i = e[i].next) { int v = e[i].to; if (v == fa) continue; dfs1(v, u); } --cnt[a[u]]; }
void dfs2(int u, int fa) { for (auto [k, id] : B[a[u]]) ans[id] -= cnt[k]; ++cnt[a[u]]; for (int i = head[u]; ~i; i = e[i].next) { int v = e[i].to; if (v == fa) continue; dfs2(v, u); } for (auto [k, id] : B[a[u]]) ans[id] += cnt[k]; }
int main() { fill(head, head + maxn, -1); ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
cin >> n >> r >> m >> a[1]; ++num[a[1]]; for (int i = 2; i <= n; ++i) { int x; cin >> x >> a[i]; add_edge(x, i); ++num[a[i]]; } for (int i = 1; i <= m; ++i) { int x, y; cin >> x >> y; if (mp.find({ x, y }) != mp.end()) { Q[i] = mp[{ x, y }]; continue; } Q[i] = mp[{ x, y }] = i; if (num[x] < num[y] || num[x] == num[y] && x < y) B[x].emplace_back(y, i); else A[y].emplace_back(x, i); } dfs1(1, 0); dfs2(1, 0); for (int i = 1; i <= m; ++i) cout << ans[Q[i]] << "\n"; return 0; }
|