Cod sursa(job #2539760)

Utilizator ioanaa_ghGhiorghi Ioana-Cristina ioanaa_gh Data 6 februarie 2020 11:46:57
Problema Asmax Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.19 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, cost;
int d[16005];
vector < int > L[16005];
queue < int > Q;

void Elimina(int i, int nod)
{
    int j, x;
    x = L[i].size();
    for(j = 0; j < x; j++)
        if(L[i][j] == nod)
    {
        L[i][j] = L[i][x - 1];
        L[i].pop_back();
        return;
    }
}

int main()
{
    int i, x, y, nod;
    fin >> n;
    for(i = 1; i <= n; i++)
        fin >> d[i];
    cost = d[1];
    for(i = 2; i <= n; i++)
        cost = max(cost, d[i]);
    for(i = 1; i < n; i++)
    {
        fin >> x >> y;
        L[x].push_back(y);
        L[y].push_back(x);
    }
    for(i = 1; i <= n; i++)
        if(L[i].size() == 1)
            Q.push(i);
    while(!Q.empty())
    {
        nod = Q.front();
        Q.pop();
        if(L[nod].size() > 0)
        {
            i = L[nod][0];
            if(d[nod] > 0)
                d[i] += d[nod];
            cost = max(cost, d[i]);
            L[nod].pop_back();
            Elimina(i, nod);
            if(L[i].size() == 1)
                Q.push(i);
        }
    }
    fout << cost << "\n";
    return 0;
}