Cod sursa(job #2822980)

Utilizator MateiDorian123Nastase Matei MateiDorian123 Data 26 decembrie 2021 15:34:16
Problema Asmax Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.13 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("asmax.in");
ofstream fout("asmax.out");

int n, s;
vector<vector<int>> g;
vector<int> c;
long long sum[16005];
bool viz[16005];

/// sum[x] = the max sum of a tree rooted in x

void citire()
{
    fin >> n;

    g.resize(n + 1);
    c.push_back(0);
    for(int i = 1; i <= n; i ++)
    {
        int x;
        fin >> x;

        c.push_back(x);
    }

    for(int i = 1; i < n; i ++)
    {
        int x, y;
        fin >> x >> y;

        g[x].push_back(y);
        g[y].push_back(x);
    }

}


void DFS(int x)
{
    viz[x] = 1;
    sum[x] = c[x];

    for(auto node : g[x])
        if(!viz[node])
        {
            DFS(node);
            sum[x] = max(sum[x], sum[node] + sum[x]); /// sum of tree rooted in x is either c[x] or sum of all children + c[x]
        }
}


int main()
{
    citire();
    fin.close();

    DFS(1);

    s = -2147483647;
    for(int i = 1; i <= n; ++i)
        if(s < sum[i])
            s = sum[i];     /// find the subtree with max sum

    fout << s;
    fout.close();
    return 0;
}