Cod sursa(job #30055)

Utilizator damaDamaschin Mihai dama Data 12 martie 2007 17:37:46
Problema Stramosi Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.63 kb
#include <stdio.h>

int mat[250000][19], n, m, sol, p, q;

int main()
{
	freopen("stramosi.in","r",stdin);
	freopen("stramosi.out","w",stdout);

	int i, j, temp, cnt;

	scanf("%d%d", &n, &m);

	for(i = 1; i <= n; ++i)
	{
		scanf("%d", &mat[i][0]);
	}

	for(j = 1; j <= 18; ++j)
	{
		for(i = 1; i <= n; ++i)
		{
			mat[i][j] = mat[mat[i][j - 1]][j - 1];
		}
	}
	
	for(i = 1; i <= m; ++i)
	{
		scanf("%d%d", &q, &p);
		sol = q;
		temp = 1 << 18;
		cnt = 18;
		while(temp)
		{
			if(temp & p)
			{
				sol = mat[sol][cnt];
			}
			temp >>= 1;
			--cnt;
		}
		printf("%d\n", sol);
	}

	return 0;
}