Cod sursa(job #2720990)

Utilizator MoiseVictor123Moise victor MoiseVictor123 Data 11 martie 2021 14:37:22
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.75 kb
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

ifstream in ("sortaret.in");
ofstream out ("sortaret.out");

const int N = 50001;

int n;
int m;
vector<int> s[N];
vector<int> a[N];
int nrp[N];
queue<int> q;

void citire() {
	in >> n >> m;
	for (int i = 0; i < m; i++) {
		int x;
		int y;
		in >> x >> y;
		a[x].push_back(y);
		a[y].push_back(x);
		s[x].push_back(y);
		nrp[y]++;
	}
	return;
}

void bfs() {
	for (int i = 1; i <= n; i++) {
		if (nrp[i] == 0) {
			q.push(i);
		}
	}
	while (!q.empty()) {
		int x = q.front();
		q.pop();
		out << x << " ";
		for (auto y : s[x]) {
			nrp[y]--;
			if (nrp[y] == 0) {
				q.push(y);
			}
		}
	}
}

int main() {
	citire();
	bfs();
	return 0;
}