Pagini recente » Borderou de evaluare (job #2500129) | Borderou de evaluare (job #2537007) | Borderou de evaluare (job #3261733) | Borderou de evaluare (job #1075318) | Cod sursa (job #2161979)
#include <iostream>
#include <fstream>
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;
ifstream fin("asmax.in");
ofstream fout("asmax.out");
vector <int > v[16001];
stack<int >f;
int n, m, a, b,maxi=-999999,mnm=-999999999, cost[16001];
void caut_frunze()
{
for(int i=1; i<=n; i++)
if(v[i].size()==1)
f.push(i);
}
void afis_arb()
{
for(int i=1; i<=n; i++)
{
cout<<i<<": ";
for(int j=0; j<v[i].size(); j++)
cout<<v[i][j]<<" ";
cout<<endl;
}
}
int main()
{
bool ok=true;
fin>>n;
for(int i=1; i<=n; i++)
{
fin>>cost[i];
if(cost[i]>mnm)
mnm=cost[i];
if(cost[i]>0)
ok=false;
}
if(ok==true)
{
fout<<mnm;
return 0;
}
for(int i=1; i<=n-1; i++)
{
fin>>a>>b;
v[a].push_back(b);
v[b].push_back(a);
}
caut_frunze();
while(!f.empty())
{
int nod=f.top();
f.pop();
while(v[nod].size()==1 && cost[nod]<0)
{
int aux=v[nod][0];
v[aux].erase(find(v[aux].begin(),v[aux].end(),nod));
v[nod].pop_back();
nod=aux;
}
while(v[nod].size()==1)
{
int aux=v[nod][0];
if(cost[aux]+cost[nod]>cost[aux])
{
cost[aux]=cost[aux]+cost[nod];
if(cost[aux]>maxi)
maxi=cost[aux];
}
v[aux].erase(find(v[aux].begin(),v[aux].end(),nod));
v[nod].pop_back();
nod=aux;
}
}
fout<<maxi;
return 0;
}