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
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;
public class Main {
public static void tSort(List<List<Integer>> list, int[] indegree) {
Queue<Integer> queue= new LinkedList<>();
Queue<Integer> result= new LinkedList<>();
for(int i = 0;i < indegree.length; i++) {
if(indegree[i] == 0) {
queue.add(i);
}
}
while(!queue.isEmpty()) {
int node = queue.poll();
result.add(node);
for(int i = 0; i < list.get(node).size(); i++) {
int n = list.get(node).get(i);
indegree[n]--;
if(indegree[n] == 0) {
queue.add(n);
}
}
}
int size = result.size();
for(int i = 0; i < size; i++) {
System.out.print(result.poll() + 1 + " ");
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int N = scan.nextInt();
int M = scan.nextInt();
List<List<Integer>> list = new ArrayList<List<Integer>>();
int[] indegree = new int[N];
for(int i = 0; i < N; i++) {
list.add(new ArrayList());
}
for(int i = 0; i < M; i++) {
int front = scan.nextInt() - 1;
int back = scan.nextInt() - 1;
list.get(front).add(back);
indegree[back]++;
}
tSort(list, indegree);
scan.close();
}
}
'알고리즘' 카테고리의 다른 글
[백준 BOJ][JAVA] 1978번: 소수 찾기 (0) | 2022.09.06 |
---|---|
[백준 BOJ][JAVA] 2960번: 에라토스테네스의 체 (0) | 2022.09.06 |
[백준 BOJ][JAVA] 11725번: 트리의 부모 찾기 (0) | 2022.02.11 |
[백준 BOJ][JAVA] 1991번: 트리 순회 (0) | 2022.02.06 |
[백준 BOJ][JAVA] 1956번: 운동 (0) | 2022.02.05 |