티스토리 뷰

https://www.acmicpc.net/problem/17839

 

17839번: Baba is Rabbit

Baba에 명령을 한 번 이상 적용한 결과로 나올 수 있는 사물을 사전순으로 출력한다. 단, 적용할 수 있는 명령이 없다면, 아무것도 출력하지 않는다.

www.acmicpc.net

 

 

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 [[N], ...CMD] = require('fs')
	.readFileSync('./dev/stdin')
	.toString()
	.trim()
	.split('\n')
	.map((v) => v.trim().split(' '));

const answer = new Set();
const pisq = new Map();

CMD.forEach(([p, is, q]) => {
	if (pisq.has(p)) {
		const arr = pisq.get(p);
		arr.push(q);
		pisq.set(p, arr);
	} else {
		const arr = [q];
		pisq.set(p, arr);
	}
});

const queue = new Queue();
queue.push('Baba');

while (queue.length > 0) {
	const p = queue.pop();
	if (pisq.has(p)) {
		for (const q of pisq.get(p)) {
			if (!answer.has(q)) {
				answer.add(q);
				queue.push(q);
			}
		}
	}
}

console.log([...answer].sort().join('\n'));
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
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
글 보관함