# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1123957 | Saul0906 | Regions (IOI09_regions) | C11 | 0 ms | 0 KiB |
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define pii pair<int,int>
#define pll pair<ll,ll>
#define fi first
#define se second
//#define endl "\n"
#define rep(a,b,c) for(ll a=b; a<c; a++)
#define rep2(a,b,c,d) for(ll a=b; a<c; a+=d)
#define repr(a,b,c) for(ll a=b-1; a>c-1; a--)
#define repa(a,b) for(const auto &a: b)
#define multicase() int t; cin>>t; while(t--)
#define fastIO() ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define valid(c) cout<<(c ? "YES" : "NO")<<endl;
#define valid2(c,a,b) cout<<(c ? a : b)<<endl;
#define pq_min(a) priority_queue<a, vector<a>, greater<a>>
#define pq_max(a) priority_queue<a>
#define pb push_back
#define ppb pop_back
#define pf push_front
#define ppf pop_front
#define mid ((l+r)>>1)
#define flush endl<<flush
using namespace std;
using namespace __gnu_pbds;
using vi = vector<int>;
using ll = long long;
template <typename T>
using ordered_set = tree<T, null_type,less<T>, rb_tree_tag,tree_order_statistics_node_update>;
mt19937_64 rnd(chrono::steady_clock::now().time_since_epoch().count());
const int lim=5e5+5, lim2=2.5e4+5;
int S[lim], H[lim], tin[lim], tout[lim], ord[lim], c1[500][lim2], c2[500][lim2], c3[500][500], timer=1;
vector<int> adj[lim];
vector<pii> c0[lim][2];
void dfs(int u){
tin[u]=timer++;
c1[H[u]][tin[u]]++;
c2[H[u]][tin[u]]++;
repa(v,adj[u]) dfs(v);
tout[u]=timer++;
c2[H[u]][timer]--;
}
void dfs2(int u){
if(H[u]<500){
rep(i,1,500){
c3[H[u]][i]+=(c1[i][tout[u]]-c1[i][tin[u]-1]);
}
}else{
c0[H[u]][0].pb({tin[u],1});
c0[H[u]][0].pb({tout[u]+1,-1});
c0[H[u]][1].pb({tout[u]+1,u});
}
repa(v,adj[u]) dfs2(v);
}
int main(){
fastIO();
int N, R, Q, r1, r2;
cin>>N>>R>>Q;
cin>>H[1];
pii pos[R+1];
rep(i,1,R+1) pos[i]={0,i};
rep(i,2,N+1){
cin>>S[i]>>H[i];
adj[S[i]].pb(i);
pos[H[i]].fi++;
}
sort(pos+1,pos+R+1);
reverse(pos+1,pos+R+1);
rep(i,1,R+1) ord[pos[i].se]=i;
rep(i,1,N+1) H[i]=ord[H[i]];
dfs(1);
rep(j,1,500){
rep(i,0,timer){
c1[j][i]+=c1[j][i-1];
c2[j][i]+=c2[j][i-1];
//cout<<c1[j][i]<<" "<<j<<" "<<i<<endl;
//cout<<c2[j][i]<<" "<<j<<" "<<i<<endl;
}
}
dfs2(1);
int ans;
while(Q--){
cin>>r1>>r2;
r1=ord[r1];
r2=ord[r2];
ans=0;
if(r1<500 && r2<500) ans=c3[r1][r2];
else if(r1<500){
#define node2 c0[r2][1][i].se
rep(i,0,c0[r2][1].size()) ans+=c2[r1][tin[node2]];
}else if(r2<500){
#define node1 c0[r1][1][i].se
rep(i,0,c0[r1][1].size()) ans+=(c1[r2][tout[node1]]-c1[r2][tin[node1]-1]);
}else{
int i=0, j=0, x=0;
#define noder1 c0[r1][0][i]
#define noder2 c0[r2][1][j]
while(j<c0[r2][1].size()){
while(i<c0[r1][0].size() && noder1.fi<=noder2.fi) x+=noder1.se, i++;
ans+=x;
j++;
}
}
cout<<ans<<endl;
}
}