티스토리 뷰
https://www.acmicpc.net/problem/14725
14725번: 개미굴
첫 번째 줄은 로봇 개미가 각 층을 따라 내려오면서 알게 된 먹이의 정보 개수 N (1 ≤ N ≤ 1000)개가 주어진다. 두 번째 줄부터 N+1 번째 줄까지, 각 줄의 시작은 로봇 개미 한마리가 보내준 먹이 정
www.acmicpc.net
// https://www.acmicpc.net/problem/14725
// 개미굴
class AntHillItem {
constructor(word, end = false) {
this.word = word;
this.end = end;
this.children = new Map();
}
hasChild(word) {
return this.children.has(word);
}
addChild(word, isEnd = false) {
if (this.children.has(word)) return;
this.children.set(word, new AntHillItem(word, isEnd));
return this.children.get(word);
}
getChild(word) {
return this.children.get(word);
}
}
class AntHill {
constructor() {
this.head = new AntHillItem('*');
}
addPath(words) {
let current = this.head;
let index = 0;
while (index < words.length) {
const word = words[index];
const isEnd = index == words.length - 1;
if (!current.hasChild(word)) {
current.addChild(word, isEnd);
}
const nextNode = current.getChild(word);
if (!nextNode) return;
current = nextNode;
index++;
}
}
print(node, depth = 0) {
if (node.end == true) return '';
return [...node.children.entries()]
.sort((a, b) => (a[0] >= b[0] ? 1 : -1))
.map(([w, c]) => {
return ['-'.repeat(2 * depth) + w, this.print(c, depth + 1)]
.filter((v) => v.length > 0)
.join('\n');
})
.join('\n');
}
}
const anthill = new AntHill();
const input = require('fs').readFileSync('./dev/stdin').toString().trim().split('\n');
input.shift();
input.forEach((p) => {
const [_, ...path] = p.split(' ');
anthill.addPath(path);
});
const result = anthill.print(anthill.head);
console.log(result);
728x90
'자료구조 알고리즘 > 백준' 카테고리의 다른 글
Node.js) 백준 8120번: Coding of Permutations (0) | 2024.03.07 |
---|---|
TS) 백준 28099번: 이상한 배열 (0) | 2024.03.06 |
Node.js) 백준 2749번: 피보나치 수 3 (0) | 2024.03.05 |
TS) 백준 2243번: 사탕상자 (0) | 2024.03.05 |
Node.js) 백준 3653번: 영화 수집 (0) | 2024.03.04 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 롱베케이션
- node.js
- 최소공통조상
- MySQL
- 그래프
- DB 생성
- 투포인터 연습
- 동적프로그래밍
- 투포인터
- 면접질문
- 서버개발
- 다이나밍프로그래밍
- MOD
- 로드나인
- 은둔청년체험
- 면접비
- 서버점검
- 개발자면접
- create databases;
- 다이나믹프로그래밍
- BFS
- 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 | 29 | 30 | 31 |
글 보관함