Cod sursa(job #2022420)

Utilizator ioanailincaMoldovan Ioana Ilinca ioanailinca Data 16 septembrie 2017 15:26:53
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.9 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

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

/* ------ GRAPH DATA ------ */

vector <vector <int>> v;
int n, m;
stack<int> stk;
vector<bool> seen;

void readGraph() {
    fin >> n >> m;
    v = vector <vector <int>> (n + 1);
    seen = vector <bool> (n + 1);
    int x, y;

    while (m--) {
        fin >> x >> y;
        v[x].push_back(y);
    }
}

void dfs(int node) {
    seen[node] = 1;
    for (int newNode: v[node]) {
        if (seen[newNode])
            continue;
        dfs(newNode);
    }
    stk.push(node);
}

void popStack() {
    while (stk.size()) {
        fout << stk.top() << ' ';
        stk.pop();
    }
}

int main()
{
    readGraph();
    for (int i = 1; i <= n; ++i) {
        if (!seen[i])
            dfs(i);
    }
    popStack();
    return 0;
}