Completion over Perfection

백준 2252 - 줄 세우기 (JAVA 자바) 본문

앨고리듬 알고리즘

백준 2252 - 줄 세우기 (JAVA 자바)

난차차 2020. 12. 2. 21:08
반응형

백준 2252 - 줄 세우기 (JAVA 자바)

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

 

 

 

문제집과 굉장히 유사한 문제입니다. 

문제집도 같이 풀어보시면 좋을 것 같습니다. 

PriorityQueue를 이용해서 풀면 됩니다. 

 

 

 

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
import java.util.*;
 
public class Main {
    
    static int n,m;
    static boolean visits[];
    static int indegree[];
 
    public static void main(String[] args) {
 
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        m = sc.nextInt();
        indegree = new int [n+1];
        visits = new boolean[n+1];
        ArrayList <Integer> list [] = new ArrayList[n+1];
        
        for(int i=0; i<=n; i++) {
            list[i] = new ArrayList<Integer>();
        }
        
        for(int i=1; i<=m; i++) {
            int tmp1 = sc.nextInt(); // 1 2
            int tmp2 = sc.nextInt(); // 3 3
            list[tmp1].add(tmp2);
            indegree[tmp2]++;
        }
        
        PriorityQueue<Integer> q = new PriorityQueue<Integer>();
        
        for(int i=1; i<=n; i++) {
            if (indegree[i]==0) {
                q.offer(i); // 1, 2가 들어감
            }
        }
        
        while(!q.isEmpty()) {
            int out = q.poll(); // 1, 2가 나옴
            System.out.print(out + " ");
            for(int i=0; i<list[out].size(); i++) {
                int next = list[out].get(i);
//                System.out.println("next값은 : " + next);
                indegree[next]--;
                if (indegree[next]==0) {
                    q.offer(next);
                }
            }
        }
    }
}
 
cs
반응형
Comments