문제 링크 : www.acmicpc.net/problem/2252
내 풀이(2021.2.10.) : 위상 정렬
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int N, M;
int indegree[32001];
vector<int> pointing[32001];
vector<int> ordered;
void topology_sort() {
queue<int> q;
for (int i = 1; i <= N; i++) {
if (indegree[i] == 0) {
q.push(i);
}
}
while (!q.empty()) {
int out = q.front(); q.pop();
ordered.push_back(out);
for (int con : pointing[out]) {
indegree[con]--;
if (indegree[con] == 0) {
q.push(con);
}
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> N >> M;
for (int i = 0; i < M; i++) {
int a, b; cin >> a >> b;
pointing[a].push_back(b);
indegree[b]++;
}
topology_sort();
for (int i = 0; i < ordered.size(); i++) {
cout << ordered[i] << ' ';
}
return 0;
}