Cod sursa(job #1321324)

Utilizator rockerboyHutter Vince rockerboy Data 18 ianuarie 2015 23:47:38
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.74 kb
#include <fstream>
#include <list>
#include <vector>

std::ifstream in ("sortaret.in");
std::ofstream out("sortaret.out");

int n, m;
std::vector< std::list<int> > x;
std::vector<int> seen;
std::list<int> sorted;

void dfs (int i)
{
    seen[i] = true;
    for (std::list<int>::iterator it=x[i].begin(); it != x[i].end(); it++)
        if (!seen[*it]) dfs (*it);
    sorted.push_front (i);
}

int main()
{
    in >> n >> m;
    x.resize (n+1);
    seen.resize (n+1, false);

    int a, b, i;
    for (i=0; i<m; i++) {
        in >> a >> b;
        x[a].push_back(b);
    }

    for (i=1; i<=n; i++) if (!seen[i]) dfs (i);

    for (std::list<int>::iterator it=sorted.begin(); it != sorted.end(); it++) out << *it << " ";
}