본문 바로가기

Algorithm/Brute Force

(C++) - 백준(BOJ) 15658 : 연산자 끼워넣기 (2)

반응형

https://www.acmicpc.net/problem/15658

 

15658번: 연산자 끼워넣기 (2)

N개의 수로 이루어진 수열 A1, A2, ..., AN이 주어진다. 또, 수와 수 사이에 끼워넣을 수 있는 연산자가 주어진다. 연산자는 덧셈(+), 뺄셈(-), 곱셈(×), 나눗셈(÷)으로만 이루어져 있다. 연산자의 개수

www.acmicpc.net

전수조사 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

수 개수 n, 수의 정보를 입력받을 일차원 배열 nums, 최솟값을 저장할 minAns, 최댓값을 저장할 maxAns, 연산자 개수를 저장할 op를 선언후 적절히 입력받습니다.

📔 풀이과정

첫 번째 수 부터 연산자를 입력받습니다.

이후 연산자별로 backtracking함수를 수행합니다. depth가 n이 되었다면 연산자가 모두 정해졌으므로 최댓값, 최솟값을 minAns, maxAns에 각각 저장해줍니다.

📔 정답출력

minAns, maxAns를 형식에 맞게 출력해줍니다.


📕 Code

#include <bits/stdc++.h>
using namespace std;

int n, nums[11], minAns = 0x3f3f3f3f, maxAns = -0x3f3f3f3f;
int op[4];

void backtracking(int depth, int result){
    if(depth == n) {
        minAns = min(minAns, result);
        maxAns = max(maxAns, result);
        return;
    }

    if(op[0]){
        op[0]--;
        backtracking(depth+1,result+nums[depth]);
        op[0]++;
    }
    if(op[1]){
        op[1]--;
        backtracking(depth+1,result-nums[depth]);
        op[1]++;
    }
    if(op[2]){
        op[2]--;
        backtracking(depth+1,result*nums[depth]);
        op[2]++;
    }
    if(op[3]){
        op[3]--;
        backtracking(depth+1,result/nums[depth]);
        op[3]++;
    }
}

int main(){
    cin >> n;
    for(int i = 0; i < n; i++) cin >> nums[i];
    for(int i = 0; i < 4; i++) cin >> op[i];
    backtracking(1, nums[0]);
    cout << maxAns << '\n' << minAns;
}

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.