Cod sursa(job #2822831)

Utilizator blxqnAlina Voiculescu blxqn Data 25 decembrie 2021 19:36:20
Problema Asmax Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.53 kb
#include <bits/stdc++.h>
using namespace std;

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

const int INF = 0x3f3f3f3f;
const int MAX = 5000; //500000 eulerian cycle
                      //100000 apm, tree diameter

class Graph
{
///PRIVATE
    int numberOfNodes;
    int numberOfEdges;
    bool directed;
    bool fromOne;  //if first node is 1 => true

    vector<vector<int>> adjacencyList;


///PUBLIC
    public:
        Graph();
        Graph(int, int, bool, bool);

        void Build(istream&);

        void DFS(int, vector<bool>&, vector<int>&);
};

int main()
{
    int numberOfNodes, numberOfEdges, startNode, maxValue;

    fin >> numberOfNodes;

    vector<bool> visited(numberOfNodes, 0);
    vector<int> nodesValues(numberOfNodes, 0);

    numberOfEdges = numberOfNodes - 1;

    Graph G(numberOfNodes, numberOfEdges, 0, 1);

    for (int i = 0; i < numberOfNodes; i++)
        fin >> nodesValues[i];

    G.Build(fin);

    startNode = 0;

    G.DFS(startNode, visited, nodesValues);

    maxValue = nodesValues[0];

    for (int i = 0; i < numberOfNodes; i++)
        maxValue = max(maxValue, nodesValues[i]);

    fout << maxValue;

    fin.close();
    fout.close();

    return 0;
}

Graph::Graph() : numberOfNodes(0), numberOfEdges(0), directed(0), fromOne(0) { }

Graph::Graph(int _numberOfNodes, int _numberOfEdges, bool _directed, bool _fromOne) : numberOfNodes(_numberOfNodes), numberOfEdges(_numberOfEdges), directed(_directed), fromOne(_fromOne)
{
    for (int i = 0; i < _numberOfNodes; i++)
        adjacencyList.push_back( {} );
        //adjacencyList.push_back(vector<int>());
}

void Graph::Build(istream &fin)
{
    for (int i = 0; i < numberOfEdges; i++)
    {
        int firstNode, secondNode;
        fin >> firstNode >> secondNode;

        if (fromOne)
        {
            firstNode--;
            secondNode--;
        }

        adjacencyList[firstNode].push_back(secondNode);
        if (!directed)
            adjacencyList[secondNode].push_back(firstNode);
    }
}

void Graph::DFS(int startNode, vector<bool> &visited, vector<int> &nodesValues)
{
    visited[startNode] = 1;

    for (unsigned int i = 0; i < adjacencyList[startNode].size(); i++)
    {
        int nextNode = adjacencyList[startNode][i];
        if (!visited[nextNode])
        {
            DFS(nextNode, visited, nodesValues);

            if (nodesValues[nextNode] > 0)
                nodesValues[startNode] += nodesValues[nextNode];
        }
    }
}