티스토리 뷰
https://www.acmicpc.net/problem/12852
12852번: 1로 만들기 2
첫째 줄에 1보다 크거나 같고, 106보다 작거나 같은 자연수 N이 주어진다.
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 fs = require('fs');
const input = +fs.readFileSync("./dev/stdin").toString().trim()
let q = new Queue();
let answer = input;
let temp = [];
let visited = new Array(input + 1).fill(input)
q.push([input])
while (q.length > 0) {
const arr = q.pop();
const L = arr.length;
if (L > answer) continue;
if (arr[L - 1] == 1) {
answer = L;
temp = arr;
break;
} else {
const last = arr[L - 1];
if (last % 3 == 0 && visited[last / 3] > L) {
visited[last / 3] = L
q.push([...arr, last / 3]);
}
if (last % 2 == 0 && visited[last / 2] > L) {
visited[last / 2] = L
q.push([...arr, last / 2]);
}
if (last - 1 > 0 && visited[last - 1] > L) {
visited[last - 1] = L
q.push([...arr, last - 1])
}
}
}
console.log(answer - 1)
console.log(temp.join(' '))
728x90
'자료구조 알고리즘 > 백준' 카테고리의 다른 글
Node.js) 백준 17070번: 파이프 옮기기 1 (0) | 2022.06.04 |
---|---|
Node.js) 백준 2098번: 외판원 순회 (★다시풀기) (0) | 2022.06.04 |
Node.js) 백준 15989번: 1, 2, 3 더하기 4 (0) | 2022.04.26 |
Node.js)백준 2240번: 자두나무 (0) | 2022.04.26 |
Node.js)백준 2670번: 연속부분최대곱 (0) | 2022.04.24 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- DB 생성
- create db
- 서버개발
- 롱베케이션
- 다이나믹프로그래밍
- 최소공통조상
- 서버점검
- 면접질문
- 투포인터 연습
- 면접비
- 투포인터
- 로드나인
- MySQL
- node.js
- 다이나밍프로그래밍
- 은둔청년체험
- 동적프로그래밍
- BFS
- 그래프
- create databases;
- MOD
- 개발자면접
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
글 보관함