반응형
2252번: 줄 세우기
첫째 줄에 N(1 ≤ N ≤ 32,000), M(1 ≤ M ≤ 100,000)이 주어진다. M은 키를 비교한 회수이다. 다음 M개의 줄에는 키를 비교한 두 학생의 번호 A, B가 주어진다. 이는 학생 A가 학생 B의 앞에 서야 한다는 의
www.acmicpc.net
★ 위상 정렬(Topological Sort)를 잘 모르면 아래 게시글을 보고 오는걸 추천드립니다.
위상 정렬(Topological sort) BFS,DFS
비순환 방향 그래프 DAG (Directed Acyclic Graph) 사이클이 없는 방향 그래프 위상 정렬(Topological sort) 모든 간선(u,v)에 대해 먼저 오는 정점 순서로 정렬이 된다. (u가 v보다 먼저 오면 u->v) 그래프가 DA..
sunrise-min.tistory.com
위상 정렬을 공부하고 한번 적용해보고 싶어서 푼 문제이기 때문에
위 게시글의 BFS 풀이법을 참고하면 아래 코드를 쉽게 이해할 수 있다.
import java.util.*;
public class Main {
static int[] dp;
static ArrayList<Integer>[] tree;
static int[] visited;
static int n;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
int m = scan.nextInt();
int[] indegree = new int[n + 1];
LinkedList<Integer>[] dag = new LinkedList[n + 1];
for (int i = 0; i < m; i++) {
int a = scan.nextInt();
int b = scan.nextInt();
if (dag[a] == null)
dag[a] = new LinkedList<Integer>();
dag[a].add(b);
indegree[b]++;
}
// indegree가 0인 경우 Queue에 넣고 -1로 만들어 준다. (방문했다는 표시)
Queue<Integer> queue = new LinkedList<Integer>();
for (int i = 1; i <= n; i++) {
if (indegree[i] == 0) {
queue.add(i);
indegree[i]--;
System.out.print(i + " ");
}
}
// 인접한 노드의 indegree 값을 1씩 감소시키고 0인 경우 Queue에 넣는다.
while (!queue.isEmpty()) {
int num = (int) queue.poll();
LinkedList<Integer> l = dag[num];
if (l == null)
continue;
for (Integer i : l) {
indegree[i]--;
if (indegree[i] == 0) {
queue.add(i);
System.out.print(i + " ");
}
}
}
}
}
반응형
'알고리즘' 카테고리의 다른 글
[백준] 2957 이진 탐색 트리 풀이 Java, BST, TreeSet (0) | 2022.07.18 |
---|---|
[백준] 2637 장난감 조립 풀이 Java, 위상 정렬 (0) | 2022.07.18 |
위상 정렬(Topological sort) BFS,DFS (0) | 2022.07.17 |
[HackerRank]Fraudulent Activity Notifications(Sort) 풀이 Java (0) | 2022.07.17 |
Tree: Height of a Binary Tree 풀이 Java (Binary Tree 높이 구하기) (0) | 2022.07.15 |
댓글