Cod sursa(job #1695358)

Utilizator al.mocanuAlexandru Mocanu al.mocanu Data 26 aprilie 2016 22:48:06
Problema Stramosi Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.82 kb
#include <stdio.h>
#include <vector>
using namespace std;

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

int anc(int x, int y){
	int pow = 0;
	while(y && x){
		if(y & 1){
			if(l[x].size() < pow + 1)
				return 0;
			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++){
		if(p[i])
			l[i].push_back(p[i]);
	}
	int ok = 1, cnt = 0;
	while(ok){
		ok = 0;
		for(int i = 1; i <= n; i++)
			if(l[i].size() > cnt && l[l[i][cnt]].size() > cnt && l[l[i][cnt]][cnt]){
				ok = 1;
				l[i].push_back(p[l[i][cnt]]);
			}
		cnt++;
	}
	for(int i = 0; i < m; i++){
		scanf("%d%d", &x, &y);
		printf("%d\n", anc(x, y));
	}
	return 0;
}