Cod sursa(job #2444678)

Utilizator EdyOnuEdy Onu EdyOnu Data 1 august 2019 06:14:52
Problema Stramosi Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.91 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>
#define  NMAX 250001 
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) {

		/*
			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];
			}
		}

	}

	int __solve(int Q, int P) {

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

		// if P is power of 2 then the answer is calculated in the matrix
		int value = __lg(P);
		if ((1 << value) == P) {
			return S[Q][value];
		}

		// calculate the nth ancestor
		int power = __lg(P), ancestor;
		for (; P != 0; power = __lg(P)) {
			ancestor = S[Q][power];
			if (!ancestor) {
				break;
			}
			P -= (1 << power), Q = ancestor;
		}

		return ancestor;
	}

	int N, S[NMAX][18];
} solver{
	ifstream{"stramosi.in"},
	ofstream{"stramosi.out"}
};


int main() {
	return 0;
}