Cod sursa(job #2539272)

Utilizator CosminMorarMorar Cosmin Andrei CosminMorar Data 5 februarie 2020 19:37:50
Problema Asmax Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.14 kb
#include <iostream>
#include <fstream>
#include <bitset>
#include <vector>
using namespace std;
ifstream fin("asmax.in");
ofstream fout("asmax.out");
int n, maxx = -2000000000;
int v[16001];
bitset<16001> f;
vector<int> nod[16001];

void readAndSet() {
    fin >> n;
    for (int i = 1; i <= n; i++)
        fin >> v[i], maxx = max(maxx, v[i]);
    for (int i = 1; i < n; i++) {
        int a, b;
        fin >> a >> b;
        nod[a].push_back(b);
        nod[b].push_back(a);
    }
}

void getMaxSum(int i) {
    int valMax = -2000000000, suma = 0;
    valMax = max(valMax, v[i]);
    suma += v[i];

    for (vector<int>::iterator it = nod[i].begin(); it != nod[i].end(); it++) {
        int j = *it;
        if (!f[j]) {
            f[j] = true;
            getMaxSum(j);

            valMax = max(valMax, v[j]);
            if (v[j] > 0)
                suma += v[j];
        }
    }

    if (suma == 0 && valMax <= 0)
        v[i] = valMax;
    else
        v[i] = suma;

    maxx = max(maxx, v[i]);
}

int main() {
    readAndSet();
    f[1] = true;
    getMaxSum(1);
    fout << maxx;
    return 0;
}