티스토리 뷰

 

14888번: 연산자 끼워넣기

첫째 줄에 수의 개수 N(2 ≤ N ≤ 11)가 주어진다. 둘째 줄에는 A1, A2, ..., AN이 주어진다. (1 ≤ Ai ≤ 100) 셋째 줄에는 합이 N-1인 4개의 정수가 주어지는데, 차례대로 덧셈(+)의 개수, 뺄셈(-)의 개수, 

www.acmicpc.net

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; 
        }
    }
}

참고자료

 

이것이 취업을 위한 코딩 테스트다 with 파이썬 - YES24

나동빈 저자의 유튜브 라이브 방송 https://www.youtube.com/c/dongbinnaIT 취준생이라면 누구나 입사하고 싶은 카카오 · 삼성전자 · 네이버 · 라인!취업의 성공 열쇠는 알고리즘 인터뷰에 있다!IT 취준생

www.yes24.com

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
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
글 보관함