Cod sursa(job #2444680)

Utilizator EdyOnuEdy Onu EdyOnu Data 1 august 2019 06:38:46
Problema Stramosi Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.99 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;

int S[250001][18];

class Solver {

public:

	explicit Solver(string&& in, string&& out) {

		FILE* fin = fopen(in.c_str(), "r"), *fout = fopen(out.c_str(), "w");

		int Q;
		vector <int> ancestors;

		// read data
		fscanf(fin, "%d %d", &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) {
			fscanf(fin, "%d", &ancestors[i]);
		}

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

		// answer the questions
		int P, X;
		while (Q--) {
			fscanf(fin, "%d %d", &X, &P);
			fprintf(fout, "%d\n", __solve(X, P));
		}
	}

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[0][i] = 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[j - 1][i]) {
					break;
				}
				S[j][i] = S[j - 1][S[j - 1][i]];
			}
		}

	}

	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[value][Q];
		}

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

		return ancestor;
	}

	int N;
};


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