Cod sursa(job #2780739)

Utilizator rares404AlShaytan - Balasescu Rares rares404 Data 7 octombrie 2021 19:22:40
Problema Asmax Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.92 kb
#include <iostream>
#include <vector>

FILE *in = fopen("asmax.in", "r"), *out = fopen("asmax.out", "w");

const int nmax = 2e5 ;

int val[1 + nmax];
int dp[1 + nmax];
std::vector<int> G[1 + nmax];

int answer;

void runDp(int node, int parent) {
    bool isLeaf = true;
    for (auto son : G[node]) {
        if (son != parent) {
            isLeaf = false;
            runDp(son, node);
            dp[node] += dp[son] * (dp[son] >= 0);
        }
    }
    if (isLeaf) {
        dp[node] = std::max(val[node], 0);
    } else {
        dp[node] += val[node];
    }
    answer = std::max(answer, dp[node]);
}

int main() {
    int n;
    fscanf(in, "%d", &n) ;
    for (int i = 1 ; i <= n ; ++ i) {
        fscanf(in, "%d", val + i) ;
    }
    int x, y ;
    for (int i = 1 ; i < n ; ++ i) {
        fscanf(in, "%d %d", &x, &y);
        G[x].push_back(y);
        G[y].push_back(x);
    }
    runDp(1, 0);
    fprintf(out, "%d", answer);
}