Cod sursa(job #1477699)

Utilizator laurageorgescuLaura Georgescu laurageorgescu Data 26 august 2015 19:47:30
Problema Asmax Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.04 kb
#include<fstream>
#include<vector>

using namespace std;

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

const int nmax = 16000;
const int inf = 1 << 30;
int ans;
int v[ nmax + 1 ], tata[ nmax + 1 ];
vector< int > g[ nmax + 1 ];

int dfs( int nod ) {
    if ( g[ nod ].size() == 0 ) {
        return v[ nod ];
    }
    int sum = 0;
    for( vector< int >::iterator it = g[ nod ].begin(); it != g[ nod ].end(); ++ it ) {
        if ( (*it) != tata[ nod ] ) {
            tata[ *it ] = nod;
            int shp = dfs( *it );
            if ( shp > 0 ) {
                sum += shp;
            }
        }
    }
    sum += v[ nod ];
    if ( sum > ans ) {
        ans = sum;
    }
    return sum;
}
int main() {
    int n;
    fin >> n;
    for( int i = 1; i <= n; ++ i ) {
        fin >> v[ i ];
    }
    for( int i = 1; i < n; ++ i ) {
        int x, y;
        fin >> x >> y;
        g[ x ].push_back( y );
        g[ y ].push_back( x );
    }
    ans = -inf;
    dfs( 1 );
    fout << ans << "\n";
    fin.close();
    fout.close();
    return 0;
}