Cod sursa(job #2553818)

Utilizator jitaruandreiJitaru Andrei Catalin jitaruandrei Data 22 februarie 2020 12:08:01
Problema Asmax Scor 20
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.95 kb
#include <bits/stdc++.h>

using namespace std;

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

long long n, val[16005], a[16000][16000], viz[16005];
long long costmax=-1e9, cost;

int dfs(int curent){
    long long k;
    viz[curent]=1;
    for(k=1;k<=n;k++){
        if(a[curent][k]==1&&viz[k]==0){
            cost+=val[k];
            costmax=max(costmax,cost);
            //cout<<k<<" "<<cost<<" "<<costmax<<endl;
            dfs(k);
            if(val[k]<0)cost-=val[k];
        }
    }
}

long long i, x, y, j;

int main()
{
    fin>>n;
    for(i=1;i<=n;i++){
        fin>>val[i];
    }
    for(i=1;i<=n-1;i++){
        fin>>x>>y;
        a[x][y]=1;
        a[y][x]=1;
    }
    /*
    for(i=1;i<=n;i++){
        for(j=1;j<=n;j++){
            fout<<a[i][j]<<" ";
        }
        fout<<endl;
    }
    */
    cost+=val[1];
    dfs(1);
    costmax=max(costmax,cost);
    fout<<costmax;
    return 0;
}