Pagini recente » Cod sursa (job #2956314) | Cod sursa (job #1156239) | Cod sursa (job #2846028) | Cod sursa (job #129928) | Cod sursa (job #318531)
Cod sursa(job #318531)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int **a, **stramos, *cul;
void dfs (int u, int timp) {
timp++;
cul[u] = 1;
int i, j, v;
for (i=1; i <= a[u][0]; ++i) {
v = a[u][i];
if (cul [v] == 0) {
stramos [v][1] = u;
for (j = 2; j <= timp; ++j)
stramos [v][j] = stramos [stramos [v][j-1]][1];
dfs (v, timp);
}
}
}
int main() {
int i, x, y, t, n, m;
FILE *f = fopen ("stramosi.in", "r"), *fout = fopen ("stramosi.out", "w");
fscanf (f, "%d %d", &n, &m);
t = (int)log (n) + 1;
a = malloc ((n+1) * sizeof (int));
stramos = malloc ((n+1) * sizeof (int));
for (i=0; i <= n; ++i) {
a [i] = malloc (45 * sizeof (int));
stramos [i] = calloc ((t+1), sizeof (int));
a [i][0] = 0;
}
for (i=1; i <= n; ++i) {
fscanf (f, "%d", &x);
a[x] [++a [x][0]] = i;
}
cul = calloc ((n+1) , sizeof (int));
for (i=1; i <= a[0][0]; ++i)
if (cul [a[0][i]] == 0) dfs (a[0][i],0);
for (i=0; i < m; ++i) {
fscanf (f, "%d %d", &x, &y);
if (y > t) fprintf (fout, "%d\n", 0);
else fprintf ( fout, "%d\n", stramos [x][y]);
}
fclose (f);
fclose (fout);
return 0;
}