Cod sursa(job #2141488)

Utilizator Data 24 februarie 2018 13:03:17 Sortare topologica 0 cpp done Arhiva educationala 1.07 kb
``````#include<iostream>
#include<algorithm>
#include<vector>
#include<utility>
#include<unordered_set>
#include<unordered_map>
#include<cmath>
using namespace std;

typedef unordered_map< int, vector<int> > Graph;
typedef unordered_set<int> uset;

void top_sort_inner(Graph &G, int node, uset &used, vector<int> &sol) {
if (used.find(node) != used.end()) {
return;
}

used.insert(node);
for (auto &v : G[node]) {
top_sort_inner(G, v, used, sol);
}
sol.push_back(node);
}

vector<int> top_sort(Graph &G) {
uset used;
vector<int> sol;
for (auto it = G.begin(); it != G.end(); it++) {
top_sort_inner(G, it->first, used, sol);
}
reverse(sol.begin(), sol.end());
return sol;
}

int main() {
freopen("sortaret.in", "r", stdin);
freopen("sortaret.out", "w", stdout);

int N, M, x, y;
cin >> N >> M;

Graph G;
for (int i = 0 ; i < M ; i++) {
cin >> x >> y;
G[x].push_back(y);
}

vector<int> sol = top_sort(G);
for (auto &v : sol) {
cout << v << ' ';
}

return 0;
}
``````