Cod sursa(job #1639482)

Utilizator qwertyuiTudor-Stefan Berbinschi qwertyui Data 8 martie 2016 12:37:20
Problema Stramosi Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.67 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

ifstream fin ("stramosi.in");
ofstream fout ("stramosi.out");

#define LOGN 20
#define NMAX 250050

int ancestor[LOGN][NMAX];
int N, M;

int main()
{
    fin >>N >>M;

    for (int i = 1; i <= N; ++i)
		fin >>ancestor[0][i];

	for (int j = 1; (1<<j) <= N; ++j)
		for (int i = 1; i <= N; ++i)
			ancestor[j][i] = ancestor[j-1][ancestor[j-1][i]];

	for (int i = 1; i <= M; ++i)
	{
        int q, p;
        fin >>q >>p;
        for (int j = 0; (1<<j) <= N; ++j)
			if ((1<<j) & p)
				q = ancestor[j][q];

		fout <<q <<'\n';
	}
    return 0;
}