Skip to content

Commit 0f00eb4

Browse files
committed
add: 백준/위상정렬
1 parent 24b1696 commit 0f00eb4

1 file changed

Lines changed: 91 additions & 0 deletions

File tree

boj/14567(위상정렬).js

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
// 선수과목(Prerequisite)
2+
// https://www.acmicpc.net/problem/14567
3+
4+
const solution = (N, graph, degree) => {
5+
const semester = new Array(N + 1).fill(0);
6+
7+
const queue = [];
8+
9+
for (let i = 1; i <= N; i++) {
10+
if (!degree[i]) {
11+
queue.push([i, 1]);
12+
}
13+
}
14+
15+
for (let i = 1; i <= N; i++) {
16+
const [index, count] = queue.shift();
17+
18+
semester[index] = count;
19+
20+
for (let i = 0; i < graph[index].length; i++) {
21+
const next = graph[index][i];
22+
23+
degree[next]--;
24+
25+
if (degree[next] === 0) {
26+
queue.push([next, count + 1]);
27+
}
28+
}
29+
}
30+
31+
return semester.slice(1).join(' ');
32+
};
33+
34+
const fs = require('fs');
35+
const stdin = (process.platform === 'linux'
36+
? fs.readFileSync('/dev/stdin').toString().trim()
37+
: `6 4
38+
1 2
39+
1 3
40+
2 5
41+
4 5
42+
`
43+
).split('\n');
44+
45+
const input = (() => {
46+
let line = 0;
47+
return () => stdin[line++];
48+
})();
49+
50+
const [N, M] = input()
51+
.split(' ')
52+
.map((each) => parseInt(each));
53+
54+
const graph = Array.from(new Array(N + 1), () => new Array());
55+
56+
const degree = new Array(N + 1).fill(0);
57+
58+
for (let i = 0; i < M; i++) {
59+
const [start, end] = input()
60+
.split(' ')
61+
.map((each) => parseInt(each));
62+
63+
graph[start].push(end);
64+
65+
degree[end]++;
66+
}
67+
68+
console.log(solution(N, graph, degree));
69+
70+
/*
71+
72+
## How
73+
위상정렬로 풀어야 하는 문제였다.
74+
75+
위상정렬이란 사이클이 없는 방향그래프(Directed Acyclic Graph)에서 모든 노드를 방향성에 거스르지 않도록 순서대로 나열하는 것을 의미한다.
76+
77+
즉, 어떤 일을 할 때 순서대로 정렬하여 순서를 찾을 수 있다.
78+
79+
위상정렬은 스택 및 큐 자료구조를 이용해 구현할 수 있다.
80+
81+
가장 낮은 degree를 큐에 enqueue하고 하나씩 dequeue 하면서 연결된 다음 degree에 해당하는 것들을 enqueue 한다.
82+
83+
위상정렬의 시간 복잡도는 O(V + E) 이다.
84+
85+
문제의 목적은 선수과목이 존재하는 상황에서 모든 과목에 대해 각 과목을 이수하려면 최소 몇 학기가 걸리는지 구하는 것이다.
86+
87+
위상정렬로 순서를 구하면서 index에 수강 학기 수를 저장하는 식으로 풀면 된다.
88+
89+
## Retrospective
90+
91+
*/

0 commit comments

Comments
 (0)