Pagini recente » Cod sursa (job #796304) | Cod sursa (job #1970405) | Cod sursa (job #2747923) | Cod sursa (job #1331800) | Cod sursa (job #2696410)
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define NMAX 250000
#define LOGN 20
int mat[NMAX][LOGN], v[NMAX];
FILE *fin, *fout;
struct pow{///am complicat putin codul cu structuri ca sa exersez lucrul pe ele
int put, exp;
};
int readInt(){
int n;
char ch;
while(!isdigit(ch = fgetc(fin)));
n = ch - '0';
while(isdigit(ch = fgetc(fin))){
n = n * 10 + ch - '0';
}
return n;
}
struct pow closestpower(int a){
struct pow putere;
putere.put = 1;
putere.exp = 0;
while(putere.put <= a){
putere.put *= 2;
putere.exp++;
}
putere.put /= 2;
putere.exp--;
return putere;
}
int main()
{
struct pow putere;
int n, m, i, j, nextval, q, p;
fin = fopen("stramosi.in", "r");
n = readInt();
m = readInt();
for(i = 0; i < n; i++){
v[i] = readInt();
v[i]--;
}
for(i = 0; i < n; i++){
for(j = 0; j < LOGN; j++){
mat[i][j] = -1;
}
}
for(i = 0; i < n; i++){
nextval = v[i];
j = 0;
while(nextval != -1){
mat[i][j] = nextval;
nextval = mat[nextval][j];
j++;
}
}
fout = fopen("stramosi.out", "w");
for(i = 0; i < m; i++){
q = readInt();
p = readInt();
q--;
while((0 < p) && (0 <= q)){
putere = closestpower( p );
q = mat[q][putere.exp];
p -= putere.put;
}
fprintf(fout, "%d\n", q + 1);
}
fclose(fin);
fclose(fout);
return 0;
}