https://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
문제
풀이
위상 정렬 문제이다. inDegree 배열을 하나 만든 다음 , 차수가 0이면 Queue에 추가 , 인접한 노드들의 InDegree 차수 1씩 감소 하는식으로 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
|
import java.util.*;
import java.io.*;
public class Main{
static int V,E;
static ArrayList<Integer>[] list;
static int[] inDegree;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] input = br.readLine().split(" ");
V = Integer.parseInt(input[0]); E = Integer.parseInt(input[1]);
list = new ArrayList[V+1];
inDegree = new int[V+1];
for(int i=1;i<=V;i++) {
list[i] = new ArrayList<>();
}
for(int i=0;i<E;i++){
input = br.readLine().split(" ");
int start = Integer.parseInt(input[0]);
int end = Integer.parseInt(input[1]);
list[start].add(end);
inDegree[end]++;
}
Queue<Integer> q = new LinkedList<>();
for(int i=1;i<=V;i++) {
if (inDegree[i] == 0){
q.add(i);
}
}
LinkedList<Integer> answer = new LinkedList<>();
while (!q.isEmpty()){
int poll = q.poll();
answer.add(poll);
for (int e : list[poll]) {
inDegree[e]--;
if(inDegree[e] == 0 )
q.add(e);
}
}
for (int e : answer) {
System.out.print(e+" ");
}
}
}
|
cs |
'알고리즘,PS > 백준' 카테고리의 다른 글
[BOJ] 백준 [1463,12852] 1로 만들기 1,2 JAVA (0) | 2021.09.14 |
---|---|
[BOJ] 백준 [1946] 신입사원 JAVA (0) | 2021.09.13 |
[BOJ] 백준 [1197] 최소 스패닝 트리 JAVA (0) | 2021.09.09 |
[BOJ] 백준 [1806] 부분합 JAVA (0) | 2021.09.08 |
[BOJ] 백준 [3273] 두 수의 합 JAVA (0) | 2021.09.08 |