Cod sursa(job #3351544)

Utilizator rapidu36Victor Manz rapidu36 Data 20 aprilie 2026 09:55:45
Problema Asmax Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.32 kb
#include <stdio.h>
#include <stdbool.h>

#define N 16000
#define NIL (-1)
#define INF 1001

struct element {
    int varf, urm;
};

typedef struct element element;

element v[2*(N-1)];
int nr_v, lst[N+1], val[N+1];
bool viz[N+1];

void init_lst(int n) {
    for (int i = 1; i <= n; i++) {
        lst[i] = NIL;
    }
}

void adauga(int x, int y) {
    // il adaugam pe y in lista lui x
    v[nr_v].varf = y;
    v[nr_v].urm = lst[x];
    lst[x] = nr_v++;
}

void dfs(int x) {
    viz[x] = true;
    for (int p = lst[x]; p != NIL; p = v[p].urm) {
        int y = v[p].varf;
        if (!viz[y]) {
            dfs(y);
            if (val[y] > 0) {
                val[x] += val[y];
            }
        }
    }
}

int main(void) {
    FILE *in, *out;
    in = fopen("asmax.in", "r");
    out = fopen("asmax.out", "w");
    int n;
    fscanf(in, "%d", &n);
    init_lst(n);
    for (int i = 1; i <= n; i++) {
        fscanf(in, "%d", &val[i]);
    }
    for (int i = 0; i < n - 1; i++) {
        int x, y;
        fscanf(in, "%d%d", &x, &y);
        adauga(x, y);
        adauga(y, x); // avem un graf neorientat
    }
    dfs(1);
    fclose(in);
    int val_max = -INF;
    for (int i = 1; i <= n; i++) {
        if (val[i] > val_max) {
            val_max = val[i];
        }
    }
    fprintf(out, "%d\n", val_max);
    fclose(out);
    return 0;
}