Cod sursa(job #1841632)

Utilizator preda.andreiPreda Andrei preda.andrei Data 5 ianuarie 2017 20:25:22
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.02 kb
#include <algorithm>
#include <fstream>
#include <vector>

using namespace std;

struct Node
{
    bool visited = false;
    vector<int> neighbours;
};

using Graph = vector<Node>;

void DFS(Graph &g, int node, vector<int> &order)
{
    g[node].visited = true;
    for (int n : g[node].neighbours)
        if (!g[n].visited)
            DFS(g, n, order);
    order.push_back(node + 1);
}

vector<int> TopoSort(Graph &g)
{
    vector<int> order;
    for (unsigned i = 0; i < g.size(); ++i)
        if (!g[i].visited)
            DFS(g, i, order);

    reverse(order.begin(), order.end());
    return order;
}

int main()
{
    ifstream fin("sortaret.in");
    ofstream fout("sortaret.out");

    int n, m;
    fin >> n >> m;

    Graph graph(n);
    while (m--) {
        int x, y;
        fin >> x >> y;
        graph[x - 1].neighbours.push_back(y - 1);
    }

    auto topo = TopoSort(graph);
    for (int node : topo)
        fout << node << " ";
    fout << "\n";

    return 0;
}