Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 누적 합
- 투 포인터
- 이분 탐색
- 모던 JavaScript 튜토리얼
- 해시 테이블
- 정렬
- boj
- 그래프
- 수학
- 2357
- 맵
- 트리
- DFS
- 에라토스테네스의 체
- 13164
- 세그먼트 트리
- 문자열
- 플로이드-워셜
- 정수론
- SSAFY
- BFS
- 슬라이딩 윈도우
- 싸피
- 애드 혹
- Python
- 구현
- JavaScript
- 브루트포스
- DP
- 그리디
Archives
- Today
- Total
흙금이네 블로그
[BOJ] 14395 - 4연산 (Python, JavaScript) 본문
아이디어
BFS와 정렬로 s를 t로 바꾸는 최소 연산 방법을 구한다.
풀이 #1 (Python)
s와 t는 모두 1 이상이므로 수를 0으로 만드는 - 연산은 사용하지 않는다.
def solution():
s, t = map(int, input().split())
if s == t:
print(0)
return
stack = [(t, '')]
exps = []
while stack:
n, exp = stack.pop()
if n == s:
exps.append(exp)
continue
elif n == 1:
exps.append('/'+exp)
continue
if int(n**0.5)**2 == n:
stack.append((int(n**0.5), '*'+exp))
if n%2 == 0:
stack.append((n//2, '+'+exp))
if exps:
print(sorted(exps, key=lambda x: (len(x), x))[0])
else:
print(-1)
solution()
풀이 #2 (JavaScript)
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().split('\n');
function solution() {
const [s, t] = input[0].split(' ').map(Number);
if (s === t) {
console.log(0);
return;
}
let stack = [[t, '']];
let exps = [];
while (stack.length) {
const [n, exp] = stack.pop();
if (n === s) {
exps.push(exp);
continue;
}
else if (n === 1) {
exps.push('/'+exp);
continue;
}
if (parseInt(n**0.5)**2 === n) stack.push([parseInt(n**0.5), '*'+exp]);
if (n%2 === 0) stack.push([parseInt(n/2), '+'+exp]);
}
if (exps.length) console.log(exps.sort((a, b) => {
if (a.length === b.length) return a < b ? -1 : 1;
else return a.length-b.length;
})[0]);
else console.log(-1);
}
solution();
'알고리즘' 카테고리의 다른 글
[BOJ] 3055 - 탈출 (Python, JavaScript) (0) | 2023.06.08 |
---|---|
[BOJ] 1963 - 소수 경로 (Python, JavaScript) (0) | 2023.06.07 |
[BOJ] 2250 - 트리의 높이와 너비 (Python, JavaScript) (0) | 2023.06.05 |
[BOJ] 16198 - 에너지 모으기 (Python, JavaScript) (0) | 2023.06.04 |
[BOJ] 14428 - 수열과 쿼리 16 (Python, JavaScript) (0) | 2023.06.02 |
Comments