Pagini recente » Cod sursa (job #2956726) | Cod sursa (job #1896817) | Cod sursa (job #479539) | Cod sursa (job #1758105) | Cod sursa (job #2500139)
#include <fstream>
#include <vector>
#include <cstring>
#define N 16000 + 1
using namespace std;
ifstream f ( "asmax.in" );
ofstream g ( "asmax.out" );
vector < int > graph[N];
bool viz[N];
int cost[N], val[N], S;
void dfs ( int node ){
viz[node] = 1;
for ( int i = 0; i < graph[node].size(); i++ ){
int new_node = graph[node][i];
if ( viz[new_node] == 0 ){
dfs ( new_node );
cost[node] = max ( cost[node], val[node] + cost[new_node] );
}
}
}
void calc ( int node ){
viz[node] = 1;
S += val[node];
for ( int i = 0; i < graph[node].size(); i++ ){
int new_node = graph[node][i];
if ( viz[new_node] == 0 && S + cost[new_node] > S )
calc ( new_node );
}
}
int main()
{ int n, i, rad, x, y;
f >> n;
for ( i = 1; i <= n; i++ ){
f >> val[i];
cost[i] = val[i];
}
f >> rad >> y;
graph[rad].push_back ( y );
graph[y].push_back ( rad );
for ( i = 2; i <= n - 1; i++ ){
f >> x >> y;
graph[x].push_back ( y );
graph[y].push_back ( x );
}
dfs ( rad );
memset ( viz, 0, sizeof ( viz ) );
calc ( rad );
g << S;
return 0;
}