Cod sursa(job #1695262)

Utilizator al.mocanuAlexandru Mocanu al.mocanu Data 26 aprilie 2016 20:50:59
Problema Stramosi Scor 10
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.67 kb
#include <stdio.h>
#include <vector>
using namespace std;

const int MAX = 250005;
int n, m, x, y, p[MAX], lvl[MAX];
vector<int> l[MAX];

int anc(int x, int y){
	int pow = 0;
	while(y && x){
		if(y & 1)
			x = l[x][pow];
		pow++;
		y >>= 1;
	}
	return x;
}

int main(){
	freopen("stramosi.in", "r", stdin);
	freopen("stramosi.out", "w", stdout);
	scanf("%d%d", &n, &m);
	for(int i = 1; i <= n; i++)
		scanf("%d", &p[i]);

	for(int i = 1; i <= n; i++){
		int x = i, niv = 0, pow = 0;
		while(x){
			x = p[x];
			niv++;
			if(niv & (1<<pow)){
				l[i].push_back(x);
				pow++;
			}
		}
	}

	for(int i = 0; i < m; i++){
		scanf("%d%d", &x, &y);
		printf("%d\n", anc(x, y));
	}
	return 0;
}