This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(0)->sync_with_stdio(0);
const int SQRT = 450;
int n, r, q, x, y, t = -1;
cin >> n >> r >> q;
vector<vector<int>> G(n + 1), regnodes(r + 1);
vector<int> tin(n + 1), tout(n + 1), reg(n + 1), nodes;
cin >> reg[1];
for (int i = 2; i <= n; ++i) {
cin >> x >> reg[i];
G[x].emplace_back(i);
G[i].emplace_back(x);
}
function<void(int, int)> dfs = [&](int node, int last) {
tin[node] = ++t;
regnodes[reg[node]].emplace_back(t);
nodes.emplace_back(node);
for (auto x : G[node])
if (x != last)
dfs(x, node);
tout[node] = t;
};
dfs(1, 0);
map<pair<int, int>, int> ans;
for (int i = 1; i <= r; ++i)
if (regnodes[i].size() >= SQRT) {
vector<int> cur(t + 2);
for (auto x : regnodes[i])
++cur[x], --cur[tout[nodes[x]] + 1];
for (int j = 1; j <= t; ++j) {
cur[j] += cur[j - 1];
ans[{i, reg[nodes[j]]}] += cur[j];
}
}
while (q--) {
cin >> x >> y;
if (regnodes[x].size() >= SQRT)
cout << ans[{x, y}] << endl;
else {
int ans = 0;
for (auto x : regnodes[x])
ans += upper_bound(regnodes[y].begin(), regnodes[y].end(), tout[nodes[x]]) - lower_bound(regnodes[y].begin(), regnodes[y].end(), x);
cout << ans << endl;
}
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |