Cod sursa(job #2882945)

Utilizator amcbnCiobanu Andrei Mihai amcbn Data 31 martie 2022 22:45:15
Problema Stramosi Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.83 kb
#include <bits/stdc++.h>
const int mod = 9901, inf = 0x3f3f3f3f;
const char sp = ' ', nl = '\n';
using namespace std;

class InParser {
private:
	FILE* fin;
	char* buff;
	int sp;

	char read_ch() {
		++sp;
		if (sp == 4096) {
			sp = 0;
			fread(buff, 1, 4096, fin);
		}
		return buff[sp];
	}

public:
	InParser(const char* nume) {
		fin = fopen(nume, "r");
		buff = new char[4096]();
		sp = 4095;
	}

	InParser& operator >> (int& n) {
		char c;
		while (!isdigit(c = read_ch()) && c != '-');
		int sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		}
		else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}

	InParser& operator >> (long long& n) {
		char c;
		n = 0;
		while (!isdigit(c = read_ch()) && c != '-');
		long long sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		}
		else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}
};

InParser 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;
	}
}