Cod sursa(job #2444685)

Utilizator EdyOnuEdy Onu EdyOnu Data 1 august 2019 06:52:56
Problema Stramosi Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.84 kb
// stramosi.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

//#include "pch.h"
#include <iostream>
#include <fstream>
#include <cmath>
#include <vector>
using namespace std;


class Solver {

public:

	explicit Solver(istream&& in, ostream&& out) {

		int Q;
		vector <int> ancestors;

		// read data
		in >> N >> Q;

		// resize the vector so that it have enough space for all numbers
		ancestors.resize(N + 1);
		for (int i = 1; i <= N; ++i) {
			in >> ancestors[i];
		}

		// do the dynamic programming magic :))
		__process(ancestors);

		// answer the questions
		int P, X;
		while (Q--) {
			in >> X >> P;
			out << __solve(X, P) << '\n';
		}
	}

private:

	int __lg(int number) const {
		return floor(log2(number));
	}

	void __process(const vector<int>& ancestors) {

		// create the empty matrix
		__intializeMatrix();

		/*
			S[i][j] = the 2 ^ j ancestor of node i
			S[i][0] = ancestors[i]
			S[i][j] = S[S[i][j-1]][j-1] while S[i][j - 1] != 0
		*/
		for (int i = 1; i <= N; ++i) {
			// first ancestor is the father
			S[i][0] = ancestors[i];

			// calculate the second, the forth, ..., ancestor of node i as long as it exists
			for (int j = 1; j <= __lg(N); ++j) {
				if (!S[i][j - 1]) {
					break;
				}
				S[i][j] = S[S[i][j - 1]][j - 1];
			}
		}

	}

	void __intializeMatrix() {

		int log = __lg(N) + 1;

		S.resize(N + 1);
		for (int i = 1; i <= N; ++i) {
			S[i].resize(log);
		}
	}

	int __solve(int Q, int P) {

		if (__lg(P) > __lg(N)) {
			return 0;
		}

		for (int j = __lg(N); j >= 0 && Q; --j) {
			if (!(P & (1 << j))) {
				continue;
			}
			Q = S[Q][j];
		}

		return Q;
	}

	int N;

	vector <vector<int>> S;
};


int main() {
	Solver{
		ifstream{"stramosi.in"},
		ofstream{"stramosi.out"}
	};
}