Cod sursa(job #2161972)

Utilizator dragosmdvMoldovan Dragos dragosmdv Data 11 martie 2018 22:27:31
Problema Asmax Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.51 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <vector>
#include <algorithm>

using namespace std;

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

vector <int > v[16001];
stack<int >f;
int n, m, a, b,maxi=-999999, cost[16001];


void caut_frunze()
{
    for(int i=1; i<=n; i++)
        if(v[i].size()==1)
            f.push(i);
}


void afis_arb()
{
    for(int i=1; i<=n; i++)
    {
        cout<<i<<": ";
        for(int j=0; j<v[i].size(); j++)
            cout<<v[i][j]<<" ";
        cout<<endl;
    }
}

int main()
{
    fin>>n;
    for(int i=1; i<=n; i++)
        fin>>cost[i];
    for(int i=1; i<=n-1; i++)
    {
        fin>>a>>b;
        v[a].push_back(b);
        v[b].push_back(a);
    }

    caut_frunze();


    while(!f.empty())
    {
        int nod=f.top();
        f.pop();
        while(v[nod].size()==1 && cost[nod]<0)
        {
            int aux=v[nod][0];

            v[aux].erase(find(v[aux].begin(),v[aux].end(),nod));
            v[nod].pop_back();
            nod=aux;
        }
        while(v[nod].size()==1)
        {
            int aux=v[nod][0];
            if(cost[aux]+cost[nod]>cost[aux])
            {
                cost[aux]=cost[aux]+cost[nod];
                if(cost[aux]>maxi)
                maxi=cost[aux];
            }
            v[aux].erase(find(v[aux].begin(),v[aux].end(),nod));
            v[nod].pop_back();
            nod=aux;
        }

    }
    fout<<maxi;


    return 0;
}