1. 문제 링크
2252번: 줄 세우기
첫째 줄에 N(1 ≤ N ≤ 32,000), M(1 ≤ M ≤ 100,000)이 주어진다. M은 키를 비교한 회수이다. 다음 M개의 줄에는 키를 비교한 두 학생의 번호 A, B가 주어진다. 이는 학생 A가 학생 B의 앞에 서야 한다는 의
www.acmicpc.net
2. 문제 및 입출력예제
3. 문제 풀이
- 두 학생의 키를 비교해 전체 학생을 줄 세우는 위상정렬 문제이다.
- 학생 전체에 대한 비교가 아니라 인접리스트를 이용했다.
- 방향 그래프를 입력받으면서 진입차수를 늘렸다.
- 진입차수가 0이 되면 큐에 넣고, 큐가 빌 때까지 큐에서 뽑으면서 인접 노드를 처리한다.
- 큐에서 뽑은 순서대로 ArrayList에 넣고 출력한다.
4. 코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Queue;
public class Main {
static class Node{
int vertex;
Node link;
public Node(int vertex, Node link) {
super();
this.vertex = vertex;
this.link = link;
}
}
static int N, M, inDegree[];
static Node[] adjList;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
String[] split = br.readLine().split(" ");
N = Integer.parseInt(split[0]); //학생 수
M = Integer.parseInt(split[1]); //비교
adjList = new Node[N+1];
inDegree = new int[N+1];
int from = 0, to = 0;
for(int i=0;i<M;i++) {
split = br.readLine().split(" ");
to = Integer.parseInt(split[0]);
from = Integer.parseInt(split[1]);
adjList[to] = new Node(from, adjList[to]);
inDegree[from]++;
}
ArrayList<Integer> list = topologysort();
for(int i: list) {
sb.append(i).append(" ");
}
System.out.println(sb);
}
private static ArrayList<Integer> topologysort() {
ArrayList<Integer> order = new ArrayList<>();
Queue<Integer> queue = new ArrayDeque<>();
for(int i=1;i<N+1;i++) {
if(inDegree[i]==0) {
queue.offer(i);
}
}
while(!queue.isEmpty()) {
int current = queue.poll();
order.add(current);
for(Node temp = adjList[current]; temp!=null; temp=temp.link) {
if(--inDegree[temp.vertex] == 0) {
queue.offer(temp.vertex);
}
}
}
return order;
}
}
'ALGORITHM' 카테고리의 다른 글
백준 10250 ACM 호텔 (Java) (0) | 2023.04.03 |
---|---|
백준 1021 회전하는 큐 (Java) (0) | 2023.04.02 |
백준 16236 아기상어 (Java) (0) | 2023.03.31 |
백준 9375 패션왕 신해빈 (Java) (0) | 2023.03.30 |
백준 1920 수 찾기 (Java) (0) | 2023.03.29 |