Cod sursa(job #2285568)

Utilizator skoda888Alexandru Robert skoda888 Data 18 noiembrie 2018 19:00:16
Problema Cerere Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.42 kb
#include <stdio.h>
#include <stdlib.h>

#define dim 8192
char ax[dim];
int pz;

typedef struct nod {
    int idx, r, g;
    struct nod *child, *next;
} nod;

int N, K, G, f, c, i;
nod **mks;
int q[100001];

void cit(int *x) {
    *x = 0;
    while (ax[pz] < '0' || ax[pz] > '9') {
        ++pz;
        if (pz == dim) fread(ax, 1, dim, stdin), pz = 0;
    }
    while (ax[pz] >= '0' && ax[pz] <= '9') {
        *x = *x * 10 + ax[pz++] - '0';
        if (pz == dim) fread(ax, 1, dim, stdin), pz = 0;
    }

}

void dfs(nod *m, nod *p, int level) {
    nod *c;
    m->r = (m->g == 0) ? 0 : mks[q[level - m->g]]->r + 1;
    c = m->child;
    while(c) {
        q[level] = m->idx;
        dfs(c, m, level + 1);
        c = c->next;
    }
}

int main() {
    int cs = 0;
    FILE *fi = freopen("cerere.in", "r", stdin);
    FILE *fo = freopen("cerere.out", "w", stdout);
    cit(&N);
    mks = (nod**) malloc(sizeof(nod*) * (N+1));
    for (i = 1; i <= N; i++) {
        cit(&G);
        mks[i] = (nod*) malloc(sizeof(nod));
        mks[i]->idx = i;
        mks[i]->g = G;
    }

    for (i = 1; i < N; i++) {
        cit(&f), cit(&c);
        cs += c;
        mks[c]->next = mks[f]->child;
        mks[f]->child = mks[c];
    }
    dfs(mks[(N * (N + 1)) /2 - cs], NULL, 1);
    for (i = 1; i <= N; i++) {
        printf("%d ", mks[i]->r);
    }
    fclose(fi);
    fclose(fo);
    return 0;
}