Cod sursa(job #2900645)

Utilizator AlexePaulAlexe Paul AlexePaul Data 11 mai 2022 18:43:06
Problema Stramosi Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.88 kb
#include <bits/stdc++.h>

#define FILE "stramosi"

using namespace std;

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

const int maxN = 350000;
const int maxL = 20;

int m[maxN+5][maxL+5], arr[maxN];
int N,M,x,y;

int prelucrare(int x, int y){
	int p = 1;
	int c = 0;
	while(p < y){
		p <<= 1;
		c++;
	}
	if(p == y)
		return m[x][c];
	p >>= 1;
	c--;
	int sol = m[x][0];
	while(y != 0){
		y -= p;
		p >>= 1;
		if(y == 0)
			break;
		sol = m[sol][c];
		c--;
	}
	return sol;
}

int main(){
	fin >> N >> M;
	m[0][0] = 0;
	for(int i = 1; i <= N; ++i){
		fin >> arr[i];
		m[i][0] = arr[i];
	}
	for(int j = 1; j < maxL; ++j){
		for(int i = 1; i <= N; ++i){
			x = m[i][j-1];
			m[i][j] = m[x][j-1];
		}
	}
/*
	for(int i = 0 ; i <= N; ++i){
		for(int j = 0 ; j <= N; ++j)
			cout << m[i][j] << ' ';
		cout << '\n';
	}
*/
	for(int i = 0; i < M; ++i){
		fin >> x >> y;
		fout << prelucrare(x,y) << '\n';
	}
}