Cod sursa(job #3370812)

Utilizator G_b_yZamfirache Gabriel G_b_y Data 27 octombrie 2026 12:46:38
Problema Asmax Scor 10
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.09 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMAX = 16005;
vector<int> vec[NMAX];
int grad[NMAX], cost[NMAX];
bool viz[NMAX];

struct el {
    int nod, cost;
    bool operator<(const el &e2) const {
        return cost > e2.cost;
    }
};

int main () {
    int n;
    in >> n;
    for (int i = 1; i <= n; ++i) {
        in >> cost[i];
    }
    for (int i = 1; i < n; ++i) {
        int a, b;
        in >> a >> b;
        vec[a].push_back(b);
        vec[b].push_back(a);
        grad[a]++;
        grad[b]++;
    }
    int total = 0, ans;
    priority_queue<el> pq;
    for (int i = 1; i <= n; ++i) {
        if (grad[i] == 1) {
            pq.push({i, cost[i]});
        }
        total += cost[i];
    }
    ans = total;
    while (!pq.empty()) {
        el fr = pq.top();
        pq.pop();
        total -= cost[fr.nod];
        ans = max(ans, total);
        for (int y : vec[fr.nod]) {
            if (!viz[y]) {
                viz[y] = true;
                pq.push({y, cost[y]});
            }
        }
    }
    out << ans;
    return 0;
}