Cod sursa(job #778588)
// stramosi.cpp : Defines the entry point for the console application.
//
//#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
unsigned int *v;
unsigned int **stramosi;
unsigned int *depth;
int get_val(int start, int depth) {
int pos = start - 1;
while (v[pos] && depth--)
pos = v[pos] - 1;
return v[pos];
}
int get_depth(unsigned int n, unsigned int i) {
unsigned pos, j;
pos = i;
j = 0;
while (v[pos]) {
j++;
pos = v[pos] - 1;
}
return j;
}
void calculate(unsigned int n) {
stramosi = new unsigned int*[n];
depth = new unsigned int[n];
for(unsigned int i = 0; i < n; i++) {
unsigned d = get_depth(n, i);
depth[i] = d;
stramosi[i] = new unsigned int[d + 1];
unsigned int j = 0, pos = i;
while (v[pos]) {
stramosi[i][j++] = v[pos];
pos = v[pos] - 1;
}
}
//for(int i = 0; i < n; i++) {
// for(int j = 0; j < depth[i]; j++)
// cout << stramosi[i][j] << " ";
// cout << " " << depth[i] << endl;
//}
//getchar();
}
void read_input(unsigned int &n, unsigned int &m) {
fstream in_file;
ofstream out_file;
unsigned int a, b;
in_file.open("stramosi.in");
in_file >> n >> m;
v = new unsigned int[n];
for(unsigned int i = 0; i < n; i++)
in_file >> v[i];
calculate(n);
out_file.open("stramosi.out");
for(unsigned int i = 0; i < m; i++) {
in_file >> a >> b;
if (depth[a - 1] < b)
out_file << 0 << endl;
else
out_file << stramosi[a - 1][b - 1] << endl;
//out_file << get_val(a, b - 1) << endl;
}
in_file.close();
out_file.close();
}
//void write_solution(int m) {
// ofstream out_file;
// out_file.open("stramosi.out");
//
// for(int i = 0; i < m; i++)
// out_file << get_val(x[i][0], x[i][1] - 1) << endl; //stramosi[x[i][0] - 1][x[i][1] - 1] << endl;
//
// out_file.close();
//}
int main()
{
unsigned int n, m;
read_input(n, m);
//calculate(n);
//write_solution(m);
//cout << n << " " << m << endl;
//for(int i = 0; i < n; i++)
// cout << v[i] << " ";
//cout << endl;
//for(int i = 0; i < m; i++)
// cout << x[i][0] << " " << x[i][1] << endl;
//getchar();
return 0;
}