Cod sursa(job #2254038)

Utilizator HerddexJinga Tudor Herddex Data 4 octombrie 2018 18:32:20
Problema Asmax Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.62 kb
#include <fstream>
using namespace std;
ifstream fin("asmax.in");
ofstream fout("asmax.out");

struct ListUnit
{
    int node;
    ListUnit *nextUnit;
};

struct Node
{
    int value;
    int numberOfNeighbors;
    ListUnit *NeighborList;
};

int main()
{
    int N;
    fin >> N;

    int Queue[16000];
    int first = 0;
    int last = -1;

    bool isDeleted[16001];
    for(int i=1; i<=N; i++)
        isDeleted[i] = false;


    bool suntToateNegative = true;
    int maxim = -1000;

    Node node[16001];
    for(int i=1; i<=N; i++)
    {
        node[i].numberOfNeighbors = 0;
        node[i].NeighborList = 0;
        fin >> node[i].value;
        if(node[i].value >= 0)
            suntToateNegative = false;
        else
            if(maxim < node[i].value)
                maxim = node[i].value;
    }

    if(suntToateNegative)
    {
        fout << maxim;
        fin.close();
        fout.close();
        return 0;
    }

    for(int e = 1; e <= N-1; e++)
    {
        int v, w;
        fin >> v >> w;

        ListUnit *newNeighbor = new ListUnit;
        newNeighbor -> node = w;
        newNeighbor -> nextUnit = node[v].NeighborList;
        node[v].NeighborList = newNeighbor;
        node[v].numberOfNeighbors++;

        newNeighbor = new ListUnit;
        newNeighbor -> node = v;
        newNeighbor -> nextUnit = node[w].NeighborList;
        node[w].NeighborList = newNeighbor;
        node[w].numberOfNeighbors++;
    }

    for(int i=1; i<=N; i++)
    {
        if(node[i].numberOfNeighbors == 1)
        {
            last++;
            Queue[last] = i;
        }
    }

    if(N==1)
    {
        fout << node[1].value;
        fin.close();
        fout.close();
        return 0;
    }

    while(first<=last)
    {
        int i = Queue[first];
        int neighbor = 0;

        for(ListUnit *p = node[i].NeighborList; p != 0; p = p -> nextUnit)
        {
            if(!isDeleted[p -> node])
                neighbor = p -> node;
        }

        if(neighbor == 0)
        {
            fout << node[i].value;
            fin.close();
            fout.close();
            return 0;
        }
        else
        {
            if(node[i].value >= 0)
                node[neighbor].value += node[i].value;
            node[neighbor].numberOfNeighbors--;
            if(node[neighbor].numberOfNeighbors == 1)
            {
                last++;
                Queue[last] = neighbor;
            }
        }
        isDeleted[i] = true;
        first++;
    }

    fin.close();
    fout.close();
    return 0;
}