프로그래밍 공방

[백준] 1766번 : 문제집 본문

개발/문제해결

[백준] 1766번 : 문제집

hyosupsong 2021. 1. 26. 20:28

문제

www.acmicpc.net/problem/1766

 

1766번: 문제집

첫째 줄에 문제의 수 N(1 ≤ N ≤ 32,000)과 먼저 푸는 것이 좋은 문제에 대한 정보의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 둘째 줄부터 M개의 줄에 걸쳐 두 정수의 순서쌍 A,B가 빈칸을 사이에 두고 주

www.acmicpc.net

문제해결방법

이 문제는 위상정렬 문제였는데 이 전에 풀었던 문제와 다른 점은 가능하면 쉬운 문제부터 풀어야 한다는 점이였다.

이 부분을 해결하기 위해 Priority Queue를 사용해서 문제집들을 정렬해서 출력해주었다.

코드

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package baekjoon;
 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
 
public class Main1766_문제집 {
 
    public static int[] need;
    public static List<Integer>[] edge;
    public static PriorityQueue<Integer> pq;
        
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int n = Integer.parseInt(st.nextToken());
        int m = Integer.parseInt(st.nextToken());
        edge = new List[n+1];
        need = new int[n+1];
        pq = new PriorityQueue<Integer>();
        for(int i=1; i<=n; i++) edge[i] = new ArrayList<Integer>();
        for(int i=0; i<m; i++) {
            st = new StringTokenizer(br.readLine());
            int A = Integer.parseInt(st.nextToken());
            int B = Integer.parseInt(st.nextToken());
            edge[A].add(B);
            need[B]+=1;
        }
        
        for(int i=1; i<=n; i++) {
            if(need[i]==0) pq.add(i);
        }
        while(!pq.isEmpty()) {
            int cur = pq.poll();
            bw.write(cur+" ");
            for(int i=0; i<edge[cur].size(); i++) {
                int next = edge[cur].get(i);
                need[next]--;
                if(need[next]==0) pq.add(next);
            }
        }
        bw.flush();
        bw.close();
        br.close();
    }
}
cs


코드에 대한 피드백이나 더 좋은 아이디어는 언제나 환영입니다.

'개발 > 문제해결' 카테고리의 다른 글

[프로그래머스] 합승 택시 요금  (0) 2021.01.26
[백준] 1010번 : 다리놓기  (0) 2021.01.26
OSI 7 Layer  (0) 2021.01.24
[프로그래머스] 셔틀버스  (0) 2021.01.23
[프로그래머스] 가사 검색  (0) 2021.01.21