반응형
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, m, a, b;
vector<int> graph[32001];
int cnt[32001] = { 0 };
priority_queue<int> pq;
int main() {
scanf("%d %d", &n, &m);
while (m--) {
scanf("%d %d", &a, &b);
graph[a].push_back(b);
cnt[b]++;
}
for (int i = 1; i <= n; i++)
if (cnt[i] == 0) pq.push(-i);
while (!pq.empty()) {
int val = -pq.top();
pq.pop();
printf("%d ", val);
for (int i = 0; i < graph[val].size(); i++) {
if (--cnt[graph[val][i]] == 0)
pq.push(-graph[val][i]);
}
}
}
반응형
'Algorithm' 카테고리의 다른 글
백준 2357 : 최솟값과 최댓값 (0) | 2021.11.15 |
---|---|
백준 2525 : 오븐 시계 (0) | 2021.11.15 |
백준 1766 : 문제집 (0) | 2021.11.15 |
백준 1011 : Fly me to the Alpha Centauri (0) | 2021.11.15 |
백준 18258 : 큐 2 (0) | 2021.11.15 |