Cod sursa(job #2821185)

Utilizator MirunaStefaniaLupascu Miruna-Stefania MirunaStefania Data 22 decembrie 2021 11:21:14
Problema Asmax Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.95 kb
#include<bits/stdc++.h>
#define N 16005
#define inf 200000000

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


int cost[N];//initial cost of nodes
int sol[N];//sol[x] --> the maximum cost of the partial that has node x "as a root"
            //
bool viz[N];//for dfs

class Graph {
private:

    int n, m;
    vector<int> adlist[N];  //adjent list


public:
    Graph() = default;
    Graph(int n  = 0, int m = 0):n(n), m(m){}

    void readUndirected();

    void dfs(int node);

};


void Graph::readUndirected() {
    for(int i = 1; i <= n-1; ++i) {

        int x, y;
        fin >> x >> y;
            adlist[x].push_back(y);
            adlist[y].push_back(x);

    }
}

void Graph::dfs(int node) {
    viz[node] = 1;
    sol[node] = cost[node];    //first of all the best sum is every node is an individual component

    for(int i = 0; i < adlist[node].size();++i)
    {
        int vertex = adlist[node][i];
        if(!viz[vertex])
        {
            dfs(vertex);
            sol[node] = max(sol[node],sol[node] + sol[vertex]);//after the recursive call check if childs come with positive cost
                                                                //update if possible
        }
    }

}


void solveDfs() { ///PARTIAL TREE WITH MINIMUM COST
    ///after the recursive dfs we update sol[x] --> the maximum cost of the partial tree that has just the nodes after x in dfs traversal
    ///x the "root" of the graph and the children are these after it

    int n;
    fin >> n;
    Graph g(n);
    for(int i = 1; i <= n; ++i)
        fin >> cost[i];
    g.readUndirected();

    g.dfs(1); //we know that it's connected
    int maxi = -inf;

    //for(int i = 1; i <= n; ++i)cout << sol[i] << " ";

    for(int i = 1; i <= n; ++i)
            if(sol[i] > maxi)
                maxi = sol[i];

     fout << maxi;
}

int main() {
    solveDfs();
    return 0;
}