티스토리 뷰

 

 

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

// https://www.acmicpc.net/problem/6615
const input = require('fs')
	.readFileSync('./dev/stdin')
	.toString()
	.trim()
	.split('\n')
	.map((v) => v.split(' ').map(Number));
input.pop();

const answer = input
	.map((v) => {
		const [A, B] = v;
		const listA = getCollatzArray(A);
		const listB = getCollatzArray(B);
		let C;
		for (let i = listA.length - 1; i >= 0; i--) {
			const target = listA[i];
			if (listB.includes(target)) {
				C = target;
			}
		}
		const stepA = listA.indexOf(C);
		const stepB = listB.indexOf(C);

		return `${A} needs ${stepA} steps, ${B} needs ${stepB} steps, they meet at ${C}`;
	})
	.join('\n');
console.log(answer);

function getCollatzArray(num) {
	const arr = [num];
	let temp = num;
	while (temp != 1) {
		if (temp % 2 == 0) {
			temp /= 2;
		} else {
			temp = 3 * temp + 1;
		}
		arr.push(temp);
	}
	return arr;
}
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
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
글 보관함