Cod sursa(job #2503344)

Utilizator Iulia25Hosu Iulia Iulia25 Data 2 decembrie 2019 21:31:47
Problema Stramosi Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.73 kb
#include <fstream>
#include <queue>

using namespace std;

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

int n, m, x, y;
int tata[250005][20];

queue <pair <int, int> > q;

inline int find_daddy(int nod, int sus)	{
	int x = 0;
	while (sus)	{
		++x;
		if (sus & 1)
			nod = tata[nod][x];
		sus >>= 1;
	}
	return nod;
}

int main()	{
	fin >> n >> m;
	for (int i = 1; i <= n; ++i)	{
		fin >> tata[i][1];
		if (tata[i][1])
			q.push({i, 1});
	}
	bool gata = false;
	while (!q.empty())	{
		int i = q.front().second;
		int j = q.front().first;
		q.pop();
		tata[j][i + 1] = tata[tata[j][i]][i];
		if (tata[j][i + 1])	 {
			q.push({j, i + 1});
		}
	}
	while (m--)	 {
		fin >> x >> y;
		fout << find_daddy(x, y) << '\n';
	}
	return 0;
}