프로그래밍 공방

[백준] 2252번 : 줄 세우기 본문

개발/문제해결

[백준] 2252번 : 줄 세우기

hyosupsong 2021. 1. 12. 22:33

문제

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

문제해결방법

이 문제는 정확한 키를 비교해서 학생의 줄을 세우는 것이 아닌 선후 관계가 정의된 그래프 상에서 선후 관계에 따라 출력을 해주는(위상정렬) 문제였다.

코드

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
53
package baekjoon;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.StringTokenizer;
 
public class Main2252_줄세우기 {
 
    public static void bfs(int x, int[] count, List<Integer>[] edge) {        
        System.out.print(x+" ");
        Queue<Integer> q = new ArrayDeque<Integer>();
        q.add(x);
        count[x]--;
        while(!q.isEmpty()) {
            int cur = q.poll();
            for(int i=0; i<edge[cur].size(); i++) {
                int next = edge[cur].get(i);
                count[next]--;
                if(count[next]==0) {
                    count[next]--;
                    System.out.print(next+" ");
                    q.add(next);
                }
            }
        }
    }
 
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int N = Integer.parseInt(st.nextToken());
        int M = Integer.parseInt(st.nextToken());
        int[] count = new int[N+1];
        List<Integer>[] edge = new List[N+1];
        for(int i=1; i<=N; i++) edge[i] = new ArrayList<>();
        for(int i=0; i<M; i++) {
            st = new StringTokenizer(br.readLine());
            int s = Integer.parseInt(st.nextToken());
            int e = Integer.parseInt(st.nextToken());
            count[e]++;
            edge[s].add(e);
        }
        for(int i=1; i<=N; i++) {
            if(count[i]==0) {
                bfs(i, count, edge);
            }
        }
    }
}
cs


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