Cod sursa(job #1815925)

Utilizator msciSergiu Marin msci Data 25 noiembrie 2016 22:24:29
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
// Kahn's algorithm for topologically sorting a DAG
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <map>
#include <set>
#include <list>
#include <functional>
using namespace std;
static const int INF = 0x3f3f3f3f; static const long long INFL = 0x3f3f3f3f3f3f3f3f;
template<typename T, typename U> static void amin(T &x, U y) { if (y < x) x = y; }
template<typename T, typename U> static void amax(T &x, U y) { if (y > x) x = y; }

struct Node {
	bool visited;
	int deg; // number of incoming edges
	vector<int> adj;
	Node() {
		visited = false;
		deg = 0;
	}
};

int N, M;
Node V[100005];
vector<int> top;
vector<int> s; // set holding the current nodes with no incoming edges;

int main() {
	freopen("sortaret.in", "r", stdin);
	freopen("sortaret.out", "w", stdout);
	cin >> N >> M;
	for (int i = 0; i < M; i++) {
		int x, y; cin >> x >> y;
		V[x].adj.push_back(y);
		V[y].deg++;
	}
	// construct S
	for (int i = 1; i <= N; i++) {
		if (V[i].deg == 0) s.push_back(i);
	}
	while (!s.empty()) {
		int node = s.back();
		top.push_back(node);
		s.pop_back();
		for (auto &i : V[node].adj) {
			int current = V[node].adj[0];
			V[current].deg--;
			V[node].adj.erase(V[node].adj.begin());
			if (V[current].deg <= 0) {
				s.push_back(current);
			}
		}
	}
	for (auto &i : top) {
		cout << i << " ";
	}
	cout << endl;
}