Cod sursa(job #928949)

Utilizator vld7Campeanu Vlad vld7 Data 26 martie 2013 19:33:41
Problema Stramosi Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.01 kb
#include <fstream>

using namespace std;

ifstream f("stramosi.in");
ofstream g("stramosi.out");

const int MAX_N = 250005;
const int MAX_logN = 20;

int n, m, tata[MAX_N];
int D[MAX_logN][MAX_N];			// D[i][j] = al 2^i-lea stramos al nodului j

// aka Smenul de la stramosi

void read() {
	f >> n >> m;
	for (int i = 1; i <= n; i++) {
		f >> tata[i];
		D[0][i] = tata[i];
	}
}

void baga_smen() {
	for (int i = 1; (1 << i) < n; i++)
		for (int j = 1; j <= n; j++)
			D[i][j] = D[i - 1][D[i - 1][j]];	// 2^(i - 1) + 2^(i - 1) = 2^i
}

int fa_smen(int Q, int P) {		// gaseste al P-lea stramos al lui Q, daca exista
	int x = 0;
	
	// tre sa gasesc x maxim ca sa am 2^x <= P
	
	for (x = 0; (1 << x) <= P; x++);
	if (x == 0)
		return Q;
	else {
		x--;
		return fa_smen(D[x][Q], P - (1 << x));
	}
}
	

int main() {
	read();
	baga_smen();
	
	for (int i = 1; i <= m; i++) {
		int Q, P;
		
		f >> Q >> P;
		g << fa_smen(Q, P) << '\n';
	}
	
	f.close();
	g.close();
	
	return 0;
}