Cod sursa(job #2539386)

Utilizator PetrescuAlexandru Petrescu Petrescu Data 5 februarie 2020 20:28:19
Problema Sortare topologica Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <fstream>
#include <vector>
#include <algorithm>
#define MAX 15000

using namespace std;

int costNod[MAX + 5], grd[MAX + 5];
int dp[MAX + 5];
vector< int >graph[MAX + 5], graphT[MAX + 5];

vector< int > sortareTopologica(int n)
{
    vector< int >Q;

    for(int i = 1; i <= n; i++)
        if(grd[i] == 0)Q.push_back(i);

    for(int i = 0; i < n; i++)
        for(auto nod : graph[Q[i]])
        {
            grd[nod]--;

            if(grd[nod] == 0)Q.push_back(nod);
        }

    return Q;
}

int main()
{
    int t;

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

    fin >> t;

    for(int cnt = 1; cnt <= t; cnt++)
    {
        int n, m;

        fin >> n >> m;

        for(int i = 1; i <= n; i++)
        {
            fin >> costNod[i];

            graph[i].clear();
            grd[i] = dp[i] = 0;
        }

        for(int i = 1; i <= m; i++)
        {
            int a, b;

            fin >> a >> b;

            graph[a].push_back(b);
            graphT[b].push_back(a);

            grd[b]++;
        }

        vector< int > sortatT = sortareTopologica(n);

        for(auto nod : sortatT)
        {
            for(auto fiu : graphT[nod])
                dp[nod] = max(dp[nod], dp[fiu]);

            dp[nod] += costNod[nod];
        }

        int solMax = 0;

        for(int i = 1; i <= n; i++)
            solMax = max(solMax, dp[i]);

        fout << solMax << '\n';
    }

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

    return 0;
}