티스토리 뷰

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

 

1897번: 토달기

첫 줄에 사전에 등재된 단어의 수 d와, 원장님이 처음 말씀하신 단어가 주어진다. (1 ≤ d ≤ 1,000) 원장님이 처음 말씀하신 단어의 길이는 세 글자이며, 사전에 있는 단어를 말씀하셨다. 다음 d개

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

const [D, N] = input.shift().split(' ');

let words = Array.from(Array(81), () => new Array());

input.forEach((word) => {
	const length = word.length;
	words[length].push(word);
});

let max = N;

const q = new Queue();

q.push(N);

while (q.length > 0) {
	const now = q.pop();

	const nowLength = now.length;
	words[nowLength + 1].forEach((next) => {
		// 한글자 차이인지 확인하고,
		// 확인되면 큐에 넣기
		if (check(now, next)) {
			if (next.length > max.length) {
				max = next;
			}
			q.push(next);
		}
	});
}
console.log(max);

function check(a, b) {
	let diff = 0;
	let j = 0;
	for (let i = 0; i < a.length; i++) {
		if (a[i] != b[j]) {
			diff++;
			i--;
		}
		if (diff == 2) {
			return false;
		}
		j++;
	}
	return true;
}
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
글 보관함