Cod sursa(job #2822964)

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

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

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

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

void citire()
{
    fin >> n;

    g.resize(n + 1);

    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 = 0;
    for(int i = 1; i <= n; ++i)
        if(sum[i] > s)
            s = sum[i];     /// find the subtree with max sum

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