Submission #1214092

#TimeUsernameProblemLanguageResultExecution timeMemory
1214092iamhereforfunRegions (IOI09_regions)C++20
45 / 100
8103 ms196608 KiB
// IamHereForFun //

#include <bits/stdc++.h>

using namespace std;

#define LSOne(X) ((X) & -(X))

const int N = 2e5 + 5;
const int M = 1e2 + 5;
const int C = 26;
const int LG = 20;
const int R = 25e3 + 5;
const int B = 450;
const int INF = 1e9 + 5;
const int MOD = 1e9 + 7;

int n, r, q, home[N], cnt_home[N], heavy[B][R], in[N], out[N], cid = 0, heavy_idx[N];
vector<pair<int, int>> range[R];
vector<int> adj[N], tour;
map<int, int> mp[N];

void dfs1(int c)
{
    in[c] = cid++;
    tour.push_back(c);
    for(int i : adj[c])
    {
        dfs1(i);
    }
    out[c] = cid++;
    tour.push_back(c);
    range[home[c]].push_back({in[c], out[c]});
}

void dfs2(int c)
{
    mp[c][home[c]]++;
    for(int i : adj[c])
    {
        dfs2(i);
        if(mp[c].size() < mp[i].size()) swap(mp[c], mp[i]);
        for(pair<int, int> p : mp[i])
        {
            mp[c][p.first] += p.second;
        }
    }
    if(cnt_home[home[c]] >= B)
    {
        for(int x = 1; x <= r; x++)
        {
            heavy[heavy_idx[home[c]]][x] += mp[c][x];
        }
    }
}

void solve()
{
    cin >> n >> r >> q;
    cin >> home[1];
    cnt_home[home[1]]++;
    for(int x = 2; x <= n; x++)
    {
        int i; cin >> i;
        adj[i].push_back(x);
        cin >> home[x];
        cnt_home[home[x]]++;
        if(cnt_home[home[x]] == B)
        {
            heavy_idx[home[x]] = cid;
            cid++;
        }
    }
    cid = 0;
    dfs1(1);
    dfs2(1);
    for(int x = 1; x <= r; x++) sort(range[x].begin(), range[x].end());
    for(int x = 0; x < q; x++)
    {
        int r1, r2; cin >> r1 >> r2;
        if(cnt_home[r1] >= B)
        {
            cout << heavy[heavy_idx[r1]][r2] << endl;
        }
        else
        {
            int ans = 0;
            for(pair<int, int> p : range[r1])
            {
                ans += lower_bound(range[r2].begin(), range[r2].end(), make_pair(p.second, 0)) - lower_bound(range[r2].begin(), range[r2].end(), make_pair(p.first, 0));
            }
            cout << ans << endl;
        }
    }
}

signed main()
{
    // freopen("CP.INP", "r", stdin);
    // freopen("CP.OUT", "w", stdout);
    // freopen("promote.in", "r", stdin);
    // freopen("promote.out", "w", stdout);
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int t = 1;
    // cin >> t;
    for (int x = 1; x <= t; x++)
    {
        solve();
    }
    return 0;
}


#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...