컴퓨터 사이언스/1고리즘
백준 2252 : 줄 세우기
저세상 개발자
2021. 8. 12. 22:46
https://www.acmicpc.net/problem/2252
2252번: 줄 세우기
첫째 줄에 N(1 ≤ N ≤ 32,000), M(1 ≤ M ≤ 100,000)이 주어진다. M은 키를 비교한 회수이다. 다음 M개의 줄에는 키를 비교한 두 학생의 번호 A, B가 주어진다. 이는 학생 A가 학생 B의 앞에 서야 한다는 의
www.acmicpc.net
현재 정점이 되는 사람보다 키가 작은 사람이 무조건 이미 앞에 존재해야하므로 위상정렬로 해결할 수 있는 문제다.
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int n;
vector<int> edge[32'001];
int pre_cnt[32'001];
vector<int> ans;
void bfs() {
int cur, next;
queue<int> q;
for (int i = 1; i <= n; i++) {
if (!pre_cnt[i]) q.push(i);
}
while (!q.empty()) {
cur = q.front();
q.pop();
ans.push_back(cur);
for (int i = 0; i < edge[cur].size(); i++) {
next = edge[cur][i];
--pre_cnt[next];
if (!pre_cnt[next]) q.push(next);
}
}
}
void solution() {
int m, from, to;
cin >> n >> m;
while (m--) {
cin >> from >> to;
edge[from].push_back(to);
++pre_cnt[to];
}
bfs();
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << ' ';
}
}
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
solution();
return 0;
}
메모리: 4148 kb | 시간: 36 ms |