티스토리 뷰
https://www.acmicpc.net/problem/1005
1005번: ACM Craft
첫째 줄에는 테스트케이스의 개수 T가 주어진다. 각 테스트 케이스는 다음과 같이 주어진다. 첫째 줄에 건물의 개수 N과 건물간의 건설순서 규칙의 총 개수 K이 주어진다. (건물의 번호는 1번부
www.acmicpc.net
골드 3단계 문제인데, Node로 풀면 골드3문제는 아닌 거 같다.
다른 언어로는 그냥 위상정렬로 통과하는데, Node에서는 시간초과 때문에 dfs + dp 로 푼 사람이 많았다.
나도 처음에는 단순히 위상정렬로 풀었는데 시간초과가 나서 입력방식을 fs 에서 readline으로 바꾸고, input값을 Array말고 Queue에 담아서 푸니까 통과했다.
다들 dp로 열심히 풀었는데, 나만 입력모듈 바꿔서 그냥 위상정렬로 풀었다고 생각하니 통과하고도 좀 찝찝하다;
class Node {
constructor(item) {
this.item = item;
this.next = null;
}
}
class Queue {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
push(item) {
const node = new Node(item);
if (this.head == null) {
this.head = node;
} else {
this.tail.next = node;
}
this.tail = node;
this.length += 1;
}
pop() {
const popItem = this.head;
this.head = this.head.next;
this.length -= 1;
return popItem.item;
}
}
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
let input = new Queue();
rl.on('line', function (line) {
input.push(line.split(' ').map(Number));
}).on('close', function () {
const T = input.pop()[0];
const answer = [];
for (let t = 0; t < T; t++) {
const [N, M] = input.pop();
let degree = Array(N).fill(0);
const adj = Array.from(Array(N), () => []);
let result = Array(N).fill(0);
let cost = input.pop();
for (let i = 0; i < M; i++) {
const [x, y] = input.pop().map((v) => v - 1);
degree[y]++;
adj[x].push(y);
}
const target = input.pop()[0] - 1;
const q = new Queue();
for (let i = 0; i < degree.length; i++) {
if (degree[i] == 0) {
q.push(i);
result[i] = cost[i];
}
}
while (q.length > 0) {
const now = q.pop();
if (now == target) {
answer.push(result[target]);
break;
}
for (let i = 0; i < adj[now].length; i++) {
const next = adj[now][i];
result[next] = Math.max(result[next], result[now] + cost[next]);
degree[next]--;
if (degree[next] == 0) q.push(next);
}
}
}
console.log(answer.join('\n'));
process.exit();
});
728x90
'자료구조 알고리즘 > 백준' 카테고리의 다른 글
Node.js) 백준 23288번: 주사위 굴리기2 (0) | 2023.07.23 |
---|---|
Node.js) 백준 2931번: 가스관 (0) | 2023.07.22 |
Node.js) 백준 1520번: 내리막 길 (0) | 2023.07.22 |
Node.js) 백준 1022번: 소용돌이 예쁘게 출력하기 (0) | 2023.07.21 |
Node.js) 백준 20058번: 마법사 상어와 파이어스톰 (0) | 2023.07.21 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- node.js
- MySQL
- 면접비
- 동적프로그래밍
- 서버점검
- create databases;
- 최소공통조상
- 로드나인
- BFS
- 면접질문
- 투포인터
- 은둔청년체험
- MOD
- 롱베케이션
- 그래프
- 서버개발
- 개발자면접
- DB 생성
- 다이나밍프로그래밍
- create db
- 투포인터 연습
- 다이나믹프로그래밍
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함