티스토리 뷰
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
'자료구조 알고리즘 > 백준' 카테고리의 다른 글
Node.js) 백준 11934번: 수 정렬하기 4 (0) | 2023.07.07 |
---|---|
Node.js) 백준 2623번: 음악프로그램 (0) | 2023.07.07 |
Node.js) 백준 14940번: 쉬운 최단거리 (0) | 2023.07.06 |
Node.js) 백준 18870번: 좌표 압축 (0) | 2023.07.06 |
Node.js) 백준 11659번: 구간 합 구하기 4 (0) | 2023.07.06 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- BFS
- 면접비
- DB 생성
- 다이나믹프로그래밍
- node.js
- 그래프
- 투포인터 연습
- 다이나밍프로그래밍
- 서버개발
- 투포인터
- MySQL
- 최소공통조상
- 로드나인
- 은둔청년체험
- create db
- 면접질문
- 롱베케이션
- 개발자면접
- 서버점검
- MOD
- 동적프로그래밍
- create databases;
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함