Cod sursa(job #1437634)

Utilizator andrei_diaconuAndrei Diaconu andrei_diaconu Data 18 mai 2015 08:09:14
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.74 kb
#include <fstream>
#include <vector>

#define NMax 50010

using namespace std;

ifstream f("sortaret.in");
ofstream g("sortaret.out");

vector<int> G[NMax];
int nodes, edges, n1, n2, postorder[NMax], counter, k;
bool mark[NMax];

void dfs(int node)
{
    mark[node] = true;

    for (vector<int>::iterator it = G[node].begin(); it != G[node].end(); it++)
        if (!mark[*it])
            dfs(*it);

    postorder[++k] = node;
}

int main()
{
    f>>nodes>>edges;

    for (int i=1; i<=edges; i++) {
        f>>n1>>n2;

        G[n1].push_back(n2);
    }

    for (int i=1; i<=nodes; i++)
        if (!mark[i])
            dfs(i);

    for (int i=k; i>=1; i--)
        g<<postorder[i]<<" ";

    return 0;
}