티스토리 뷰

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

 

17626번: Four Squares

라그랑주는 1770년에 모든 자연수는 넷 혹은 그 이하의 제곱수의 합으로 표현할 수 있다고 증명하였다. 어떤 자연수는 복수의 방법으로 표현된다. 예를 들면, 26은 52과 12의 합이다; 또한 42 + 32 + 1

www.acmicpc.net

const input = +require('fs').readFileSync('./dev/stdin').toString().trim();
let answer = Infinity;
const sqrtArr = [];

let num = 1;
while (num * num <= input) {
	sqrtArr.push(num * num);
	num++;
}
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 q = new Queue();
q.push([input, 0])
let dp = Array(50000).fill(Infinity);
while (q.length > 0) {
	const [value, cnt] = q.pop();
	if (value == 0 && cnt < answer) {
		answer = cnt;
	} else {
		for (let i = sqrtArr.length - 1; i >= 0; i--) {
			const sqrt = sqrtArr[i];
			const nextValue = value - sqrt;
			if (nextValue >= 0 && cnt + 1 <= answer && dp[nextValue] > cnt + 1) {
				dp[nextValue] = cnt + 1;
				q.push([nextValue, cnt + 1]);
			}
		}
	}
}
console.log(answer);
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
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
글 보관함