Pagini recente » Cod sursa (job #1524712) | Cod sursa (job #2387244) | Cod sursa (job #253820) | Cod sursa (job #2965699) | Cod sursa (job #2822964)
#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;
}