#include<bits/stdc++.h>
using namespace std;
const int MX = 200005;
struct FenwickTree {
vector<int> bit; // binary indexed tree
int n = MX;
int sum(int r) {
if(bit.empty()) bit.resize(n);
int ret = 0;
for (; r >= 0; r = (r & (r + 1)) - 1)
ret += bit[r];
return ret;
}
int sum(int l, int r) {
return sum(r) - sum(l - 1);
}
void add(int idx, int delta) {
if(bit.empty()) bit.resize(n);
for (; idx < n; idx = idx | (idx + 1))
bit[idx] += delta;
}
};
const int B = 400;
int N, R, Q;
vector <int> g[MX], region[MX];
int H[MX], st[MX], en[MX], timer=1;
int found[MX];
map <int, vector <int>> prep;
void Flat(int v, int p) {
st[v] = timer++;
if(!found[H[v]]) {
found[H[v]] = st[v];
region[H[v]].push_back(v);
}
for(auto to : g[v]) if(to!=p) {
Flat(to, v);
}
en[v] = timer-1;
if(found[H[v]]==st[v]) {
found[H[v]] = 0;
}
}
int main() {
cin >> N >> R >> Q;
cin >> H[1];
for(int i=2; i<=N; ++i) {
cin >> p >> H[i];
g[p].push_back(i);
}
Flat(1, 1);
vector <int> bigs;
for(int i=1; i<=R; ++i) if(region[i].size()>B) {
bigs.push_back(i);
}
int sz_big = bigs.size();
FenwickTree A;
for(int all=1; all<=25000; ++all) {
for(auto it : region[all]) {
A.add(st[it], 1);
}
for(auto b : bigs) {
if(prep[b].empty()) prep[b].resize(25001);
for(auto it : region[b]) {
prep[b][all] = A.sum(st[it], en[it]);
}
}
for(auto it : region[all]) {
A.add(st[it], -1);
}
}
map <int, FenwickTree> sb;
for(auto b : bigs) {
for(auto it : region[b]) {
sb[b].add(st[it], 1);
}
}
while(Q--) {
int r1, r2;
cin >> r1 >> r2;
int ans = 0;
if(region[r1].size()>B) {
ans = prep[r1][r2];
} else {
if(region[r2].size()>B) {
for(auto it : region[r1]) {
ans += sb[r2].sum(st[it], en[it]);
}
} else {
int p1 = 0, p2 = 0;
while(p1<region[r1].size() && p2<region[r2].size()) {
auto ok = [&] (int p1, int p2) {
return st[region[r1][p1]]<=st[region[r2][p2]] &&
st[region[r1][p1]]>=st[region[r2][p2]];
};
while(p2<region[r2].size() && ok(p1, p2)) ++p2, ++ans;
++p1;
}
}
cout << ans << endl;
}
}
return 0;
}
Compilation message
regions.cpp: In function 'int main()':
regions.cpp:50:10: error: 'p' was not declared in this scope
50 | cin >> p >> H[i];
| ^
regions.cpp:93:13: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
93 | while(p1<region[r1].size() && p2<region[r2].size()) {
| ~~^~~~~~~~~~~~~~~~~~
regions.cpp:93:37: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
93 | while(p1<region[r1].size() && p2<region[r2].size()) {
| ~~^~~~~~~~~~~~~~~~~~
regions.cpp:98:14: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
98 | while(p2<region[r2].size() && ok(p1, p2)) ++p2, ++ans;
| ~~^~~~~~~~~~~~~~~~~~
regions.cpp:58:6: warning: unused variable 'sz_big' [-Wunused-variable]
58 | int sz_big = bigs.size();
| ^~~~~~