Cod sursa(job #733534)

Utilizator andunhillMacarescu Sebastian andunhill Data 12 aprilie 2012 13:58:08
Problema Stramosi Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.44 kb
#include<fstream>
#include<iostream>
#include<vector>
using namespace std;

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

int N, M, NrC;

vector<int>graph[250001];
vector<int>chains[250001];
vector<int>roots;
typedef vector<int>::iterator it;

int dad[250001];
int pos_in[250001];	//pos of node i in it's chain
int which[250001];	//the chain that node i belongs to

int DFS(int node)
{	int son, max_son = 0;
	
	for(it i = graph[node].begin(); i != graph[node].end(); i++)
	{	int temp = DFS(*i);
		if(max_son < temp) max_son = temp, son = *i;
	}
	
	if(max_son == 0)
	{	chains[++NrC].push_back(node);
		which[node] = NrC;
		pos_in[node] = 0;
		return 1;
	}
	
	chains[which[son]].push_back(node);
	which[node] = which[son];
	pos_in[node] = chains[which[son]].size() - 1;
	return max_son + 1;
}

int get(int node, int nr)
{	int chain = which[node];
	//cout<<chain<<" ";
	if(node == 0) return 0;
	if(pos_in[node] + nr < chains[chain].size()) return chains[chain][pos_in[node] + nr];
	
	return get(dad[chains[chain].back()], nr - (chains[chain].size() - pos_in[node]));
}

int main()
{	int i, j;
	int P, Q;
	
	f>>N>>M;
	for(i = 1; i <= N; i++)
	{	f>>dad[i];
		if(dad[i])
			graph[dad[i]].push_back(i);
		else roots.push_back(i);
	}
	
	for(it k = roots.begin(); k != roots.end(); k++)
		DFS(*k);
	
	for(i = 1; i <= M; i++)
	{	f>>Q>>P;
		g<<get(Q, P)<<'\n';
	}
	
	f.close();
	g.close();
	return 0;
}