Submission #1265763

#TimeUsernameProblemLanguageResultExecution timeMemory
1265763newbie_tRegions (IOI09_regions)C++20
100 / 100
3064 ms35676 KiB
#include <bits/stdc++.h>
using namespace std;
#define siz(x) (int)x.size()
#define pb push_back
#define all(x) x.begin(), x.end()
//===========================================
const int MAX = 2e5+5;
const int BLOCK = 500;
vector<int> adj[MAX], comp[MAX], occ[MAX];
int cmp[MAX], in[MAX], sub[MAX], res[400][25005], pp[MAX], curr;

int dfs(int v){
    in[v] = ++curr;
    occ[cmp[v]].pb(in[v]);
    for (int u: adj[v]) sub[v] += dfs(u);
    return (sub[v] += 1);
}

void dfs2(int v, int tar, int curr){ //Go through each node as e2
    if (cmp[v] == tar) curr++;
    res[pp[tar]][cmp[v]] += curr;
    for (int u: adj[v]) dfs2(u, tar, curr);
}

int main(){
    cin.tie(0)->sync_with_stdio(0);
    int n, r, q; cin >> n >> r >> q;
    for (int i = 1; i <= n; i++){
        if (i > 1){
            int a; cin >> a;
            adj[a].pb(i);
        }
        cin >> cmp[i];
        comp[cmp[i]].pb(i);
    }
    dfs(1);
    curr = 0;
    for (int i = 1; i <= r; i++){
        if (siz(comp[i]) < BLOCK) continue;
        pp[i] = ++curr;
        dfs2(1, i, 0);
    }
    while (q--){
        int a, b; cin >> a >> b;
        if (pp[a]) cout << res[pp[a]][b] << endl;
        else {
            int tot = 0;
            for (int v: comp[a])
                tot += lower_bound(all(occ[b]), in[v]+sub[v])-lower_bound(all(occ[b]), in[v]);
            cout << tot << endl;
        }
    }
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...