티스토리 뷰
POINT
DFS
주어진 연산자를 순열 알고리즘을 사용해서 풀었으나, 중복된 연산이 많고 비효율적이라 메모리 초과가 발생한다.
→ 한 연산에서 시작하여 나머지 연산을 수행하는 모든 경우를 구하기 위해 DFS를 사용한다.
-0
JS에서는 -0이 출력이 된다. 백준에서 -0은 0이 아니므로 오답이다. 결과가 -0이면 0으로 바꿔주자.
문제풀이
const fs = require("fs");
const input = fs.readFileSync("/dev/stdin").toString().trim().split("\n");
const n = Number(input[0]);
const aList = input[1].split(" ").map(e => Number(e));
// 각 연산자 개수
let [add, sub, mul, div] = input[2].split(" ").map(e => Number(e));
let maxValue = -1e9;
let minValue = 1e9;
dfs(1, aList[0]);
console.log(maxValue);
console.log(minValue);
function dfs(index, currentValue) {
if (index === n) {
// 연산 완료 -> 최대, 최소 구하기
maxValue = Math.max(maxValue, currentValue);
minValue = Math.min(minValue, currentValue);
} else {
if (add > 0) {
add -= 1;
dfs(index + 1, currentValue + aList[index]);
add += 1; // 되돌리기
}
if (sub > 0) {
sub -= 1;
dfs(index + 1, currentValue - aList[index]);
sub += 1;
}
if (mul > 0) {
mul -= 1;
dfs(index + 1, currentValue * aList[index]);
mul += 1;
}
if (div > 0) {
div -= 1;
let result = currentValue / aList[index];
// 나눗셈 결과가 음수면 천장, 아니면 바닥
if (result < 0) {
result = Math.ceil(currentValue / aList[index]);
} else {
result = Math.floor(currentValue / aList[index]);
}
// -0 출력 주의
if (result === -0) result = 0;
dfs(index + 1, result);
div += 1;
}
}
}
참고자료
'🧩 코딩테스트' 카테고리의 다른 글
[백준] 14719 빗물 - node.js (1) | 2023.06.13 |
---|---|
[백준] 18428 감시 피하기 - Node.js (1) | 2023.05.02 |
[백준] 14501 퇴사 - Python (0) | 2022.11.16 |
[백준] 6603 로또 - Python (0) | 2022.11.14 |
[백준] 1182 부분수열의 합 - Python (0) | 2022.11.14 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- React
- 웅진IT
- 판례암기
- 동기
- rn
- backtracking
- Python3
- 코테
- 프로젝트
- node.js
- 프로그래머스
- 코딩테스트
- 비동기
- Unsplash
- React.js
- 코어자바스크립트
- 백준
- DP
- flutter
- fetch
- 다이나믹프로그래밍
- p5js
- 키워드밑줄
- 감시피하기
- dfs
- python
- 파이썬
- Spotify
- React-native
- 코드분석
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함