Pagini recente » Cod sursa (job #1844362) | Cod sursa (job #377464) | Cod sursa (job #2841844) | Castel3 | Cod sursa (job #318640)
Cod sursa(job #318640)
#include <stdio.h>
#include <stdlib.h>
int **a, **stramos, *has, *p, *q;
void dfs (int u, int timp) {
timp++;
int i, j, v, aux, curent, prec;
for (i=1; i <= a[u][0]; ++i) {
v = a[u][i];
if (has [v] == 1) {
prec = stramos [v][1];
for (j = 2; j <= timp; ++j) {
curent = stramos [prec][1];
prec = curent;
for (aux=2; aux<=stramos[v][0]; ++aux)
if (stramos [v][aux] == j) stramos[v][aux] = -curent;
}
dfs (v, timp);
}
else dfs (v, timp);
}
}
int main() {
int i, x, n, m;
FILE *f = fopen ("stramosi.in", "r"), *fout = fopen ("stramosi.out", "w");
fscanf (f, "%d %d", &n, &m);
a = malloc ((n+1) * sizeof (int));
has = calloc ((n+1) , sizeof (int));
p = malloc ((m+1) * sizeof (int));
q = malloc ((m+1) * sizeof (int));
stramos = malloc ((n+1) * sizeof (int));
for (i=0; i <= n; ++i) {
a [i] = malloc (1 * sizeof (int));
stramos [i] = calloc (3, sizeof (int));
stramos [i][0] = 1;
a [i][0] = 0;
}
for (i=1; i <= n; ++i) {
fscanf (f, "%d", &x);
a[x] = realloc (a[x], (a[x][0] + 2) * sizeof (int));
a[x] [++a [x][0]] = i;
stramos [i][1] = x;
}
for (i=0; i < m; ++i) {
fscanf (f, "%d %d", &p[i], &q[i]);
if (q[i] > 1) {
has [p[i]] = 1;
x = stramos [p[i]][0];
stramos [p[i]] = realloc (stramos [p[i]], (x + 2) * sizeof (int));
stramos [p[i]][++stramos [p[i]][0]] = q[i];
q[i] = stramos [p[i]][0];
}
}
for (i=1; i <= a[0][0]; ++i)
dfs (a[0][i],0);
for (i=0; i < m; ++i)
if (q[i] == 1) fprintf ( fout, "%d\n", stramos[p[i]][1]);
else if (stramos[p[i]][q[i]] > 0 ) fprintf (fout, "0\n");
else fprintf ( fout, "%d\n", -stramos[p[i]][q[i]]);
fclose (f);
fclose (fout);
return 0;
}