Submission #1220063

#TimeUsernameProblemLanguageResultExecution timeMemory
1220063comgaTramAnhRegions (IOI09_regions)C++17
3 / 100
1721 ms26512 KiB
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 2e5 + 5;
const int R = 25005;
const int S = 500;
int n, r, q, in[N], out[N], T = 0, c[N],id[N], hid = 0;
int Hea[S][R], cnt[R];
vector<int> g[N];
vector<pair<int,int>> reg[R];

void dfs(int x,int p = 0){
    in[x] = ++T;
    for(int j : g[x]) if(j != p){
        dfs(j,x);
    }
    out[x] = ++T;
}

void Dfs(int x, int ty, int de){
    if(c[x] == ty) de++;
    Hea[id[ty]][c[x]] += de;
    for(int i : g[x]) Dfs(i,ty,de);
}

int main(){
    ios::sync_with_stdio(0);cin.tie(0);
    cin >> n >> r >> q;
    int x;cin >> c[1];
    for(int i = 2 ; i <= n ; ++i){
        cin >> x >> c[i];
        g[x].push_back(i);
        cnt[c[i]]++;
    }
    dfs(1);
    for(int i = 1 ; i <= n ; ++i) reg[c[i]].push_back({in[i],out[i]});

    for(int i = 1 ; i <= r ; ++i)
        if((int)cnt[i] >= S) {
            id[i] = hid++;
            Dfs(1,i,0);
        }
    int u, v;



    while(q--){
        cin >> u >> v;
        if((int)cnt[u] >= S){
            cout << Hea[id[u]][v] << endl;
        }
        else{
            int ans = 0;
            for(pair<int,int> i : reg[u]){

//                cout <<lower_bound(reg[v].begin(),reg[v].end(),make_pair(i.second,0)) - reg[v].begin() << ' '
//                 << lower_bound(reg[v].begin(),reg[v].end(),make_pair(i.first,0)) - reg[v].begin() << '\n';

                ans += lower_bound(reg[v].begin(),reg[v].end(),make_pair(i.second,0))
                 - lower_bound(reg[v].begin(),reg[v].end(),make_pair(i.first,0));
            }
            cout << ans << endl;
        }
    }
    return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...