Post

baekjoon 1766:문제집

baekjoon 1766 문제집

1766번 문제집

접근

처음보자 마자 위상정렬 문제라는 것을 알 수 있었다. 한 가지 다른 점이라면
이 문제에선 더 쉬운문제를 먼저 풀어야 하므로 우선 순위 큐를 이용해서 항상 가장
작은 수를 뽑아내도록 했다.

코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//1766
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int main(){
  ios::sync_with_stdio(false);
  cin.tie(0); cout.tie(0);
  int n, m; cin >> n >> m;
  vector<vector<int>> adj(n);
  for(int i = 0; i < m; i++){
    int a, b; cin >> a >> b;
    adj[a-1].push_back(b-1);
  }
  vector<int> indegree(n);
  for(int i = 0; i < n; i++){
    for(int j : adj[i]){
      indegree[j]++;
    }
  }
  priority_queue<int, vector<int>, greater<int>> q;
  for(int i = 0; i < n; i++){
    if(indegree[i] == 0) q.push(i);
  }
  while(!q.empty()){
    int cur = q.top(); q.pop();
    cout << cur+1 << " ";
    for(int next : adj[cur]){
      indegree[next]--;
      if(indegree[next] == 0) q.push(next);
    }
  }
  
  return 0;
}

배운 점

This post is licensed under CC BY 4.0 by the author.