Cod sursa(job #709873)

Utilizator andrici_cezarAndrici Cezar andrici_cezar Data 8 martie 2012 17:34:52
Problema Stramosi Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.07 kb
#include <cstdio>

long a[20][250020], N, Q, st, nr, i, j, aux;

inline int log2(long x) {
	long nr = 0;
	
	for (; x > 1 && x % 2 == 0; x /= 2, ++nr);
	if (x > 1) ++nr;
	for (; x > 1; x /= 2, ++nr);
	
	return nr;
}

inline bool test(long x) {
	long nr = 0;
	while (x > 0) {
		nr += x & 1;
		x >>= 1;
	}
	return (nr==1)?true:false;
}

int stramos(long st, long nr) {
	if (st == 0) {
		return 0;
	}else if (test(nr) && a[log2(nr)][st] != 0) {
			return a[log2(nr)][st];
	} else {
		long pow2 = 1<<log2(nr);
		while (a[log2(pow2)][st] == 0 && pow2 != 0) 
			pow2 >>= 1;
		return stramos(a[log2(pow2)][st], nr-pow2);
	}
}

int main() {
	freopen("stramosi.in","r",stdin);
	freopen("stramosi.out","w",stdout);
	
		scanf("%ld %ld", &N, &Q);
		
		for (i = 1; i <= N; ++i) {
			scanf("%ld", &a[0][i]);
		}
		
		for (i = 1, aux = log2(N); i <= aux; ++i) {
			for (j = 1; j <= N; ++j) {
				a[i][j] = a[i-1][ a[i-1][j] ];
			}
		}
		
		for (i = 0; i < Q; ++i) {
			scanf("%ld %ld", &st, &nr);
			printf("%ld\n", stramos(st, nr));
		}
	
	return 0;
}