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;
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
template <class T> using Tree = tree<T, null_type, less<T>,
rb_tree_tag, tree_order_statistics_node_update>;
int n, r, q;
int R[200000];
vector<int> adj[200000];
vector<int> A[200001];
int start[200000], End[200000];
Tree<int> regions[200001];
int ctr = 0;
void dfs(int u) {
start[u] = ctr;
for (int v : adj[u]) {
dfs(v);
}
End[u] = ctr++;
regions[R[u]].insert(End[u]);
}
int main() {
cin >> n >> r >> q;
for (int i = 0; i < n; i++) {
if (i == 0) {
cin >> R[i];
} else {
int p;
cin >> p >> R[i];
adj[p-1].push_back(i);
}
A[R[i]].push_back(i);
}
dfs(0);
map<pair<int, int>, long long> cache;
for (int i = 0; i < q; i++) {
int a, b; cin >> a >> b;
if (cache.count(make_pair(a, b))) {
cout << cache[make_pair(a, b)] << endl;
continue;
}
bool swapped = false;
if (A[a].size() > A[b].size()) {
//swap(a, b);
//swapped = true;
}
long long ans = 0;
for (int n : A[a]) {
int x = start[n], y = End[n];
ans += regions[b].order_of_key(y) - regions[b].order_of_key(x);
}
cout << ans << endl;
if (swapped) swap(a, b);
cache[make_pair(a, b)] = ans;
}
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |