Cod sursa(job #2764959)

Utilizator DragosC1Dragos DragosC1 Data 23 iulie 2021 21:40:47
Problema Asmax Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.91 kb
#include <fstream>
#include <vector>
using namespace std;

int n;
int Max;
int cost[16001];
int dp[16001];

vector<int> a[16001];

void read() {
    int i, x, y;
    ifstream f("asmax.in");
    f >> n;
    for (i = 1; i <= n; i++)
        f >> cost[i];
    for (i = 1; i < n; i++) {
        f >> x >> y;
        a[x].push_back(y);
        a[y].push_back(x);
    }
    f.close();
}

void dfs(int x, int px) {
    for (int y : a[x]) 
        if (y != px) {
            dfs(y, x);
            dp[x] += dp[y];
        }
    dp[x] = max(0, dp[x] + cost[x]);
    if (dp[x] > Max)
        Max = dp[x];
}

void solve() {
    int i;
    Max = -16000 * 1000 - 1;
    for (i = 1; i <= n; i++)
        Max = max(Max, cost[i]);
    dfs(1, 0);
}

void output() {
    ofstream g("asmax.out");
    g << Max;
    g.close();
}

int main() {
    read();
    solve();
    output();
    return 0;
}