Cod sursa(job #1616973)

Utilizator TeodorCotetCotet Teodor TeodorCotet Data 27 februarie 2016 12:21:36
Problema Asmax Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.21 kb
#include <bits/stdc++.h>
 
using namespace std;
 
ifstream fin("asmax.in");
ofstream fout("asmax.out");
 
const int NMAX = 16000;
const int INF = 0x7fffffff;
 
int n; 
 
int cost[NMAX + 1];
 
int best[NMAX + 1]; //best[i] = cel mai bun cost care se poate forma cu un subarbore cu radacina in i, care il cuprinde pe i
                    //considerand ca radacina este in nodul 1
 
vector<int> g[NMAX + 1];
 
int smax = -INF;
 
 bool in[NMAX + 1]; int rad;
 
void read() {
 
    fin >> n; 
 
    for(int i = 1; i <= n ; ++i)
        fin >> cost[i];
 
    for(int i = 1; i < n ; ++i) {
 
        int x; int y;
        fin >> x >> y;
 
        g[x].push_back(y);
 
        in[y] = true;
    }
}
 
void dfs(int node) {
 
    for(int x : g[node])
            dfs(x);
 
    best[node] = cost[node];
 
    for(int x : g[node])
        if(best[x] > 0)
            best[node] += best[x];
 
    if(best[node] > smax) smax = best[node];
 
}
 
void solve() {
 
    for(int i = 1; i <= n; ++i)
        if(in[i] == false) {
            rad = i; break;
        }
 
    dfs(rad);
 
    fout << smax << '\n'; 
 
}
 
int main() {
 
    read();
 
    solve();
 
    return 0;
}