Cod sursa(job #1713532)

Utilizator retrogradLucian Bicsi retrograd Data 5 iunie 2016 20:22:54
Problema Stramosi Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.84 kb
#include <bits/stdc++.h>

using namespace std;

const int kMaxN = 250005;
const int kSqrt = 333;

int Depth[kMaxN], Parent[kMaxN], Link[kMaxN];
vector<int> G[kMaxN];

void dfs(int node) {
	for(auto vec : G[node]) {
		Depth[vec] = Depth[node] + 1;
		Parent[vec] = node;

		if(Depth[vec] % kSqrt)
			Link[vec] = Link[node];
		else
			Link[vec] = node;
		
		dfs(vec);
	}
}

int kth(int node, int k) {
	int seek_d = Depth[node] - k;
	if(seek_d <= 0) return 0;

	while(Depth[Link[node]] > seek_d)
		node = Link[node];
	while(Depth[node] != seek_d)
		node = Parent[node];

	return node;
}

int main() {
	ifstream cin("stramosi.in");
	ofstream cout("stramosi.out");

	int n, m, p;
		
	cin >> n >> m;
	for(int i = 1; i <= n; ++i) {
		cin >> p;
		G[p].push_back(i);
	}

	dfs(0);

	while(m--) {
		int a, b;
		cin >> a >> b;
		cout << kth(a, b) << '\n';
	}

	return 0;
}