Cod sursa(job #2709388)

Utilizator teofilotopeniTeofil teofilotopeni Data 20 februarie 2021 11:33:44
Problema Sortare topologica Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.71 kb
#include <iostream>
#include <vector>
#include <stack>
using namespace std;

//  Sortare topologica

vector<stack<short>> nodes;

void parcurge(short index) {
    if (nodes[index].empty() || nodes[index].top() != -1) {

        for (; nodes[index].size(); nodes[index].pop())
            parcurge(nodes[index].top());
        cout << index << ' ';
        nodes[index].push(-1);
    }
}

int main() {
	freopen("sortaret.in", "r", stdin);
	freopen("sortaret.out", "w", stdout);
	int n, m, x, y;
	scanf("%d %d", &n, &m);
	nodes = vector<stack<short>>(n + 1);
	while (m--) {
        scanf("%d %d", &x, &y);
        nodes[y].push(x);
	}
	for (x = 1; x <= n; x++)
        parcurge(x);
	return 0;
}