Algorithm&CodingTest/Baekjoon
[Baekjoon] [1766] 위상정렬 골드2 - 문제집
kitez
2023. 3. 15. 18:14
https://www.acmicpc.net/problem/1766
1766번: 문제집
첫째 줄에 문제의 수 N(1 ≤ N ≤ 32,000)과 먼저 푸는 것이 좋은 문제에 대한 정보의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 둘째 줄부터 M개의 줄에 걸쳐 두 정수의 순서쌍 A,B가 빈칸을 사이에 두고 주
www.acmicpc.net
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split("\n");
const [N, M] = input.shift().split(" ").map(n => Number(n));
const graph = new Array(N+1).fill(0).map(i => []);
const indegree = new Array(N+1).fill(0);
for(let i = 0 ; i < M ; i++) {
const [to, from] = input[i].split(' ').map(n => Number(n));
graph[to].push(from);
indegree[from]++;
}
const tOrder = [];
const queue = [];
for(let i = 1; i < graph.length ; i ++) {
if(indegree[i] === 0) {
queue.push(i);
break;
}
}
while(queue.length) {
const node = queue.shift();
indegree[node] = -1;
const targetNode = graph[node];
targetNode.forEach((i) => {
indegree[i]--;
});
tOrder.push(node);
for(let i = 1; i < graph.length ; i ++) {
if(indegree[i] === 0) {
queue.push(i);
break;
}
}
}
console.log(tOrder.join(" "))
728x90