Pagini recente » Cod sursa (job #1647863) | Cod sursa (job #627967) | Cod sursa (job #2504785) | Cod sursa (job #624593) | Cod sursa (job #324477)
Cod sursa(job #324477)
#include<iostream>
using namespace std;
int main()
{
int n,m;
int pmax = 0;
FILE *in = fopen("stramosi.in", "r");
FILE *out = fopen("stramosi.out", "w");
fscanf(in,"%d %d",&n,&m);
//int mat[100][10];
int nn = n;
while(nn) {
++pmax;
nn = nn>>1;
}
--pmax;
//cout << pmax;
int ** mat = (int**)malloc( (n+1)*sizeof(int *) );
for(int i = 0 ; i<=n ; ++i) {
mat[i] = (int *) malloc( (pmax+1)*sizeof(int));
}
for(int i = 0; i<=pmax; ++i)
mat[0][i] = 0;
for(int j = 1; j <= n; ++j) {
fscanf(in,"%d",&mat[j][0]);
for(int i=1;i<=pmax; ++i){
mat[j][i] = mat[mat[j][i-1]][i-1];
}
}
//cout<<pmax;
int p,q,j;
int k;
for( int i = 1; i<= m; ++i) {
fscanf(in,"%d %d",&q,&p);
if(p >= n)
q = 0;
//k = 1<<pmax;
j = pmax;
k = 1<<pmax;
for(; q && p ;) {
//cout<< k;
if( k <= p) {
p -= k;
q = mat[q][j];
}
k = k>>1, --j;
}
fprintf(out,"%u\n",q);
}
fclose(in);
fclose(out);
return 0;
}