Cod sursa(job #2882944)

Utilizator amcbnCiobanu Andrei Mihai amcbn Data 31 martie 2022 22:43:28
Problema Stramosi Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.92 kb
#include <bits/stdc++.h>
const int mod = 9901, inf = 0x3f3f3f3f;
const char sp = ' ', nl = '\n';
using namespace std;
ifstream fin("stramosi.in");
ofstream fout("stramosi.out");

namespace kth_ancestor {
	vector<vector<int>> t;
	// t[i][j] = 2^i'th ancestor of node j
	void build(int n, vector<int>& root) {
		t.assign(log2(n) + 1, vector<int>(n + 2));
		for (int i = 1; i <= n; ++i) {
			t[0][i] = root[i];
		}
		for (int i = 1; (1 << i) <= n; ++i) {
			for (int j = 1; j <= n; ++j) {
				t[i][j] = t[i - 1][t[i - 1][j]];
			}
		}
	}
	int querry(int i, int k) {
		for (int j = 0; (1 << j) <= k; ++j) {
			if ((k >> j) & 1) {
				i = t[j][i];
			}
		}
		return i;
	}
}

int main() {
	int n, q;
	fin >> n >> q;
	vector<int> v(n + 2);
	for (int i = 1; i <= n; ++i) {
		fin >> v[i];
	}
	kth_ancestor::build(n, v);
	while (q--) {
		int i, k;
		fin >> i >> k;
		fout << kth_ancestor::querry(i, k) << nl;
	}
}