Cod sursa(job #3306832)

Utilizator livliviLivia Magureanu livlivi Data 14 august 2025 14:21:35
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.79 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>

using namespace std;

void dfs(int node, const vector<vector<int>>& edges, vector<bool>& viz,
		vector<int>& topo) {
	viz[node] = true;

	for (auto next : edges[node]) {
		if (!viz[next]) {
			dfs(next, edges, viz, topo);
		}
	}

	topo.push_back(node);
}

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

	int n, m; cin >> n >> m;

	vector<vector<int>> edges(n);
	for (int i = 0; i < m; i++) {
		int a, b; cin >> a >> b;
		a--; b--;

		edges[a].push_back(b);
	}

	vector<bool> viz(n);
	vector<int> topo;
	for (int i = 0; i < n; i++) {
		if (!viz[i]) {
			dfs(i, edges, viz, topo);
		}
	}
	reverse(topo.begin(), topo.end());

	for (auto i : topo) {
		cout << i + 1 << " ";
	}
	cout << "\n";
	return 0;
}