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>
typedef long long int ll;
#define INF (1e9 + 7)
#define INF2 (998244353)
#define N (ll)2e5 + 5
using namespace std;
//#define int ll
int n, g, h, t1, t2, cur = 1, q, R;
int d[N], st[N], en[N], par[N][20], r[N];
vector<int> v[N], sts[N], ens[N], r2[N];
map<int, int> m[N];
void dfs(int x, int p){
st[x] = cur++;
sts[r[x]].push_back(cur - 1);
r2[r[x]].push_back(x);
par[x][0] = p;
for(int i = 1; i<=20; i++){
par[x][i] = par[par[x][i - 1]][i - 1];
}
for(auto u : v[x]){
if(u != p)dfs(u, x);
}
en[x] = cur++;
ens[r[x]].push_back(cur - 1);
}
void solve(){
cin >> n >> R >> q;
cin >> r[1];
for(int i=2; i<=n; i++){
cin >> g >> r[i];
v[g].push_back(i);
}
dfs(1, 0);
for(int i=1; i<=q; i++){
cin >> g >> h;
if(m[g][h]){
cout << m[g][h] - 1 << endl;
continue;
}
if(sts[g].size() > sts[h].size()){
int sum=0;
for(auto u : r2[h]){
t1 = lower_bound(sts[g].begin(), sts[g].end(), st[u]) - sts[g].begin();
t2 = lower_bound(ens[g].begin(), ens[g].end(), st[u]) - ens[g].begin();
sum += t1 - t2;
}
m[g][h] = sum + 1;
cout << sum << endl;
}
else{
int sum=0;
for(auto u : r2[g]){
t1 = lower_bound(ens[h].begin(), ens[h].end(), st[u]) - ens[h].begin();
t2 = lower_bound(ens[h].begin(), ens[h].end(), en[u]) - ens[h].begin();
sum += t2 - t1;
}
m[g][h] = sum + 1;
cout << sum << endl;
}
}
}
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
int T = 1;
//cin>>T;
while (T--){
solve();
}
}
Compilation message (stderr)
regions.cpp: In function 'void dfs(int, int)':
regions.cpp:23:19: warning: iteration 19 invokes undefined behavior [-Waggressive-loop-optimizations]
23 | par[x][i] = par[par[x][i - 1]][i - 1];
| ~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~
regions.cpp:22:21: note: within this loop
22 | for(int i = 1; i<=20; i++){
| ~^~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |