Cod sursa(job #3165396)

Utilizator AleXutzZuDavid Alex Robert AleXutzZu Data 6 noiembrie 2023 09:12:42
Problema Asmax Scor 20
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.08 kb
#include <iostream>
#include <fstream>
#include <vector>

constexpr const int MAX_N = 16000;

struct Graph {
private:
    std::vector<std::vector<int>> adj;

public:
    Graph() {
        adj.resize(MAX_N + 1);
    }

    void add_edge(int x, int y) {
        adj[x].push_back(y);
        adj[y].push_back(x);
    }

    const std::vector<int> &operator[](int idx) const {
        return adj[idx];
    }
};

std::vector<int> val = std::vector<int>(MAX_N + 1, 0);
std::vector<int> dp = std::vector<int>(MAX_N + 1, 0);

Graph tree;

void dfs(int node, int root) {
    for (const auto &x: tree[node]) {
        if (x == root) continue;
        dfs(x, node);
        dp[node] = std::max(dp[node], dp[node] + dp[x]);
    }
    dp[node] = std::max(0, dp[node] + val[node]);
}

int main() {
    std::ifstream input("asmax.in");
    std::ofstream output("asmax.out");

    int n;
    input >> n;
    for (int i = 1; i <= n; ++i) input >> val[i];


    for (int i = 0; i < n - 1; ++i) {
        int x, y;
        input >> x >> y;
        tree.add_edge(x, y);
    }

    dfs(1, 0);
    output << dp[1];
    return 0;
}