Cod sursa(job #2952563)

Utilizator AndreiBadAndrei Badulescu AndreiBad Data 9 decembrie 2022 15:35:07
Problema Asmax Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.21 kb
//
//  main.cpp
//  Asmax
//
//  Created by Andrei Bădulescu on 09.12.22.
//

//#include <iostream>
#include <fstream>
#include <bitset>
#include <vector>

using namespace std;

ifstream cin("asmax.in");
ofstream cout("asmax.out");

const int N = 16000;

bitset <N + 1> visited;
vector <int> bridges[N + 1];

int costs[N + 1];
long long results[N + 1];
int n;

void dfs(int current) {
    visited[current] = true;
    long long maxCost = 0;
    
    for (auto next: bridges[current]) {
        if (!visited[next]) {
            dfs(next);
            
            if (results[next] > 0) {
                maxCost += results[next];
            }
        }
    }
    
    results[current] = (maxCost + costs[current] > 0) ? maxCost + costs[current] : 0;
}

int main() {
    cin >> n;
    
    for (auto i = 1; i <= n; i++) {
        int cost;
        cin >> cost;
        costs[i] = cost;
    }
    
    for (auto i = 1; i <= n; i++) {
        int x, y;
        cin >> x >> y;
        
        bridges[x].push_back(y);
        bridges[y].push_back(x);
    }
    
    dfs(1);
    
    long long result = 0;
    
    for (auto i = 1; i <= n; i++) {
        result = max(result, results[i]);
    }
    
    cout << result;
    return 0;
}