Nu aveti permisiuni pentru a descarca fisierul grader_test32.ok
Cod sursa(job #318645)
Utilizator | Data | 28 mai 2009 21:14:42 | |
---|---|---|---|
Problema | Stramosi | Scor | 0 |
Compilator | c | Status | done |
Runda | Arhiva de probleme | Marime | 2.08 kb |
#include <stdio.h>
#include <stdlib.h>
int **a, **stramos, *has, *p, *q;
int insert (int *a, int x, int n) {
int i, j;
for (i=2; i < n; ++i)
if (a [i] > x) break;
for (j=n+1; j > i; --j)
a[j] = a[j-1];
a[j] = x;
return i;
}
void dfs (int u, int timp) {
timp++;
int i, j, v, aux = 2, 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;
if (stramos [v][aux] == j) {
stramos[v][aux] = -curent;
aux++;
}
}
dfs (v, timp);
}
else dfs (v, timp);
}
}
int main() {
int i, x, t, 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]][0];
t = insert (stramos [p[i]], q[i], stramos [p[i]][0]);
q[i] = t;
}
}
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;
}