Cod sursa(job #2281409)

Utilizator marcudanfDaniel Marcu marcudanf Data 12 noiembrie 2018 10:42:44
Problema Stramosi Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.66 kb
#include <iostream>
#include <fstream>
#include <vector>

const int NMAX = 25e4+5;

using namespace std;

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

int LOG[NMAX];
int a[20][NMAX];

int n, m;

void precalculate(){
	for(int i = 2; i <= n; i++)
		LOG[i] = LOG[i/2] + 1;
	for(int i = 1; 1<<i <= n; i++)
		for(int j = 1; j <= n; j++)
			a[i][j] = a[i-1][a[i-1][j]];
}

int stramos(int q, int p){
	while(p){
		int k = LOG[p];
		q = a[k][q];
		p = p - (1 << k);
	}
	return q;
}

int main(){
	fin >> n >> m;
	for(int i = 1; i <= n; i++)
		fin >> a[0][i];
	precalculate();
	while(m--){
		int q, p;
		fin >> q >> p;
		fout << stramos(q, p) << '\n';
	}
	return 0;
}