Pagini recente » Cod sursa (job #8311) | Cod sursa (job #1324899) | Cod sursa (job #406337) | Cod sursa (job #1730021) | Cod sursa (job #1658827)
#include <stdio.h>
#define MAX_VARFURI 16000
#define NECALCULAT -1000000
#define INFINIT 1000000000
int v[ MAX_VARFURI ];
int din[ MAX_VARFURI ];
int nrm[ MAX_VARFURI ];
int list[ MAX_VARFURI ][ MAX_VARFURI - 1 ];
struct muchie {
int a , b;
} muchii[ MAX_VARFURI - 1 ];
//maximul dintre a si b
int max( int a , int b ) {
if( a > b )
return a;
else
return b;
}
//calculeaza subarborele maxim cu radacina in varf
int asmax( int varf , int n ) {
//daca suma nu este calculata o calculam
if( din[ varf ] == NECALCULAT ) {
int i , nod , m;
//includ si nodul curent
din[ varf ] = v[ varf ];
//iau fiecare copil al nodului curent si caut suma maxima in acel nod
//il adaug la suma daca este pozitiv
for( i = 0 ; i < nrm[ varf ] ; i++ ) {
m = list[ varf ][ i ];
if( muchii[ m ].a == varf || muchii[ m ].b == varf ) {
nod = muchii[ m ].a + muchii[ m ].b - varf;
muchii[ m ].a = muchii[ m ].b = -1;
din[ varf ] += max( 0 , asmax( nod , n ) );
}
}
}
return din[ varf ];
}
int main() {
int n , i , rez , a , b;
FILE *fin = fopen( "asmax.in" , "r" );
fscanf( fin , "%d" , &n );
//citim valorile din fiecare nod
for( i = 0 ; i < n ; i++ ) {
fscanf( fin , "%d" , &v[ i ] );
din[ i ] = NECALCULAT;
}
//citim muchiile
for( i = 0 ; i < n - 1 ; i++ ) {
fscanf( fin , "%d%d" , &muchii[ i ].a , &muchii[ i ].b );
muchii[ i ].a--;
muchii[ i ].b--;
a = muchii[ i ].a;
b = muchii[ i ].b;
list[ a ][ nrm[ a ] ] = i;
nrm[ a ]++;
list[ b ][ nrm[ b ] ] = i;
nrm[ b ]++;
}
fclose( fin );
//cautam suma maxima
rez = -INFINIT;
for( i = 0 ; i < n ; i++ )
rez = max( rez , asmax( i , n ) );
FILE *fout = fopen( "asmax.out" , "w" );
fprintf( fout , "%d" , rez );
fclose( fout );
return 0;
}