Cod sursa(job #1761928)

Utilizator razvan242Zoltan Razvan-Daniel razvan242 Data 23 septembrie 2016 08:41:07
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.93 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMAX = 5e4 + 1;
const int notVisited = 0;
const int inProgress = 1;
const int visited = 2;

vector<int> v[NMAX];
vector<int> ans;
int viz[NMAX], n, m;

void dfs(int node) {
    viz[node] = inProgress;
    for (const int& x: v[node])
        if (viz[x] == notVisited)
            dfs(x);
    viz[node] = visited;
    ans.push_back(node);
}

inline void topologicalSort() {
    for (int i = 1; i <= n; ++i) {
        if (viz[i] == notVisited)
            dfs(i);
    }
}

inline void answer() {
    for (vector<int>::reverse_iterator it = ans.rbegin(); it != ans.rend(); ++it)
        fout << *it << ' ';
}

int main()
{
    fin >> n >> m;
    int x, y;
    for (; m; --m) {
        fin >> x >> y;
        v[x].push_back(y);
    }
    topologicalSort();
    answer();
    return 0;
}