Submission #206501

#TimeUsernameProblemLanguageResultExecution timeMemory
206501jhnah917Regions (IOI09_regions)C++14
100 / 100
4847 ms35780 KiB
#include <bits/stdc++.h>
#define all(v) v.begin(), v.end()
#define x first
#define y second
using namespace std;

typedef pair<int, int> p;

int n, r, q;
int arr[202020];
vector<int> g[202020];

int in[202020], pv;
int sz[202020];
vector<int> g1[25252], g2[25252];

map<p, int> mp;

int dfs(int v){
	in[v] = ++pv; sz[in[v]] = 1;
	g1[arr[v]].push_back(in[v]);
	for(auto i : g[v]){
		sz[in[v]] += dfs(i);
	}
	g2[arr[v]].push_back(pv);
	return sz[in[v]];
}

int q1(int a, int b){
	int ret = 0;
	for(auto i : g1[a]){
		int x = lower_bound(all(g1[b]), i + sz[i]) - g1[b].begin();
		int y = lower_bound(all(g1[b]), i) - g1[b].begin();
		ret += x - y;
	}
	return ret;
}

int q2(int a, int b){
	int ret = 0;
	for(auto i : g1[b]){
		int x = upper_bound(all(g1[a]), i) - g1[a].begin();
		int y = lower_bound(all(g2[a]), i) - g2[a].begin();
		ret += x - y;
	}
	return ret;
}

int main(){
	ios_base::sync_with_stdio(0); cin.tie(0);
	cin >> n >> r >> q;
	cin >> arr[1];
	for(int i=2; i<=n; i++){
		int t; cin >> t >> arr[i];
		g[t].push_back(i);
	}
	dfs(1);
	for(int i=0; i<25252; i++) sort(all(g2[i]));

	while(q--){
		int a, b; cin >> a >> b;
		if(mp.find({a, b}) != mp.end()){
			cout << mp[{a, b}] << endl; continue;
		}
		int ans;
		if(g1[a].size() < g1[b].size()) ans = mp[{a, b}] = q1(a, b);
		else ans = mp[{a, b}] = q2(a, b);
		cout << ans << endl;
	}
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...