Cod sursa(job #2531759)

Utilizator memecoinMeme Coin memecoin Data 26 ianuarie 2020 18:19:01
Problema Asmax Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.27 kb
#include <fstream>
#include <string>
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <math.h>
#include <set>
#include <map>
#include <string.h>
#include <queue>

#define INF 0x3f3f3f3f

using namespace std;

#ifdef DEBUG
string name = "data";
#else
string name = "asmax";
#endif

ifstream fin(name + ".in");
ofstream fout(name + ".out");

#define MAXN 16001

int n;

int best[MAXN];
int cost[MAXN];

vector<int> g[MAXN];

bool vis[MAXN];

int solve(int x) {
    if (best[x] != -INF) {
        return best[x];
    }
    
    best[x] = cost[x];
    
    vis[x] = true;
    
    for (auto y: g[x]) {
        if (vis[y]) {
            continue;
        }
        
        int child = solve(y);
        
        if (child > 0) {
            best[x] += child;
        }
    }
    
    vis[x] = false;
    
    return best[x];
}

int main() {
    
    fin >> n;
    
    for (int i = 1; i <= n; ++i) {
        int x;
        fin >> x;
        cost[i] = x;
        best[i] = -INF;
    }
    
    for (int i = 0; i < n - 1; ++i) {
        int x,y;
        fin >> x >> y;
        
        g[x].push_back(y);
        g[y].push_back(x);
    }
    
    int sol = -INF;
    
    for (int i = 1; i <= n; ++i) {
        sol = max(sol, solve(i));
    }
    
    fout << sol;
    
    return 0;
}