BOJ/미해결

BOJ 14888 - 연산자 끼워넣기

yanJuicy 2024. 9. 14. 12:08
반응형

문제

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

 

 

풀이

백트래킹을 이용해 문제를 해결한다

 

백트래킹의 핵심 코드는 다음과 같다

operator[i] -= 1
backtracking(index + 1, sum)
operator[i] += 1
sum = temp

해당 연산자는 사용했으므로 operator[i] -= 1을 해준다

operator[i] == 0 이라면 연산자를 모두 사용했다는 뜻이다

 

이후 연산자를 1개 사용한 채로 backtracking(index + 1, sum)을 실행한다

이는 다음 인덱스와 지금까지 계산한 결과값을 넘겨준다

 

다음으로 operator[i] += 1을 다시 해준다

백트래킹 이전으로 연산자를 다시 선택하지 않은 상태로 만든다

 

마지막으로 sum 값을 다시 원래 값인 temp로 돌린다

이것도 백트래킹 이전으로 sum 값을 원래 값으로 다시 돌려서 다른 연산자로 백트래킹을 새로 시작하기 위함이다

 

 

코드

python

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
32
33
34
35
36
37
38
39
40
41
42
def backtracking(index, sum):
    global minAns
    global maxAns
 
    if index == n - 1:
        if minAns > sum:
            minAns = sum
        if maxAns < sum:
            maxAns = sum
        return
 
    for i in range(4):
        temp = sum
        if operator[i] == 0:
            continue
        if i == 0:
            sum += numArr[index + 1]
        elif i == 1:
            sum -= numArr[index + 1]
        elif i == 2:
            sum *= numArr[index + 1]
        else:
            if sum < 0
                sum = abs(sum) // numArr[index + 1* - 1
            else:
                sum //= numArr[index + 1]
        
        operator[i] -= 1
        backtracking(index + 1, sum)
        operator[i] += 1
        sum = temp
 
 
= int(input())
numArr = list(map(int, input().split()))
operator = list(map(int, input().split()))
minAns = 1000000001
maxAns = -1000000001
 
backtracking(0, numArr[0])
print(maxAns)
print(minAns)
cs

 

java

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
 
public class Main {
 
    static int N, max, min;
    static int[] nums, operators, order;
    static FastReader scan = new FastReader();
 
    public static void main(String[] args) {
        input();
        rec_func(1);
        System.out.println(max + "\n" + min);
    }
 
    // 피연산자 2개와 연산자가 주어졌을 때 계산해주는 함수
    static int calculator() {
        int value = nums[1];
        for (int i=1; i<=N-1; i++) {
            if (order[i] == 1)
                value = value + nums[i + 1];
            if (order[i] == 2)
                value = value - nums[i + 1];
            if (order[i] == 3)
                value = value * nums[i + 1];
            if (order[i] == 4)
                value = value / nums[i + 1];
        }
        return value;
    }
 
    // order[1...N-1]에 연산자들이 순서대로 저장될 것이다.
    static void rec_func(int k) {
        if (k == N) {
            // 완성된 식에 맞게 계산을 해서 정답에 갱신하는 작업
            int value = calculator();
            max = Math.max(value, max);
            min = Math.min(value, min);
        } else {
            // k 번째 연산자는 무엇을 선택할 것인가?
            for (int cand=1; cand<=4; cand++) {
                if (operators[cand] >= 1) {
                    operators[cand]--;
                    order[k] = cand;
                    rec_func(k + 1);
                    operators[cand]++;
                    order[k] = 0;
                }
            }
        }
    }
 
    static void input() {
        N = scan.nextInt();
        order = new int[N + 1]; // 연산자
        nums = new int[N + 1];
        operators = new int[5];
 
        for (int i=1; i<=N; i++)
            nums[i] = scan.nextInt();
        for (int i=1; i<=4; i++)
            operators[i] = scan.nextInt();
 
        min = Integer.MAX_VALUE;
        max = Integer.MIN_VALUE;
    }
 
    static class FastReader {
        BufferedReader br;
        StringTokenizer st;
 
        public FastReader() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }
 
        public FastReader(String s) throws FileNotFoundException {
            br = new BufferedReader(new FileReader(new File(s)));
        }
 
        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
 
        int nextInt() {
            return Integer.parseInt(next());
        }
 
        long nextLong() {
            return Long.parseLong(next());
        }
 
        double nextDouble() {
            return Double.parseDouble(next());
        }
 
        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
}
 
cs

 

반응형

'BOJ > 미해결' 카테고리의 다른 글

BOJ 14502 - 연구소  (1) 2024.09.18
BOJ 2206 - 벽 부수고 이동하기  (2) 2024.09.16
BOJ 1019 - 책 페이지  (1) 2024.08.28
BOJ 14500 - 테트로미노  (0) 2024.08.27
BOJ 1436 - 영화감독 숌  (0) 2024.08.23