Cod sursa(job #2230997)

Utilizator gabriel-mocioacaGabriel Mocioaca gabriel-mocioaca Data 12 august 2018 16:34:41
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.84 kb
#include <iostream>
#include <vector>
#include <list>
#include <stack>
#include <fstream>

#define cin in
#define cout out

using namespace std;

void ts(int x, vector<list<int>> &graph, vector<bool> &vis, stack<int> &top_sort) {
	vis[x] = true;

	for (auto it : graph[x]) {
		if (!vis[it])
			ts(it, graph, vis, top_sort);
	}

	top_sort.push(x);
}

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

	int n, m, i, x, y;
	
	cin >> n >> m;
	
	vector<list<int>> graph(n + 1);
	vector<bool> vis(n + 1, false);
	stack<int> top_sort;

	for (i = 1; i <= m; ++i) {
		cin >> x >> y;
		graph[x].push_back(y);
	}

	for (i = 1; i <= n; ++i) {
		if (!vis[i]) {
			ts(i, graph, vis, top_sort);
		}
	}

	

	while (!top_sort.empty()) {
		cout << top_sort.top() << ' ';
		top_sort.pop();
	}

	return 0;
}