본문 바로가기
알고리즘/그래프

[java 백준] 실버 1/ 14888번 연산자 끼워넣기

by Meaning_ 2022. 7. 3.
728x90
반응형

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

 

14888번: 연산자 끼워넣기

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

www.acmicpc.net

 

 

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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
 
public class Main {
 
    public static int n;
    public static int m;
    public static int arr[];
    public static int add;
    public static int sub;
    public static int mul;
    public static int div;
    public static int min= Integer.MAX_VALUE;
    public static int max= Integer.MIN_VALUE;
 
    public static void DFS(int depth,int ans){
 
        if(depth==n){
            min=Math.min(ans,min);
            max=Math.max(ans,max);
        }else{
            if(add>0){
                add-=1;
                DFS(depth+1,ans+arr[depth]);
                add+=1;
            }
            if(sub>0) {
                sub -= 1;
                DFS(depth + 1, ans - arr[depth]);
                sub+=1;
            }
            if(mul>0){
                mul-=1;
                DFS(depth+1,ans*arr[depth]);
                mul+=1;
            }
            if(div>0){
                div-=1;
                DFS(depth+1,ans/arr[depth]);
                div+=1;
            }
        }
 
    }
 
    public static void main(String[]args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st ;
        n = Integer.parseInt(br.readLine());
        arr=new int[n];
 
 
 
 
        st=new StringTokenizer(br.readLine());
        for(int i=0;i<n;i++){
            arr[i]= Integer.parseInt(st.nextToken());
 
        }
 
 
        st=new StringTokenizer(br.readLine());
        add=Integer.parseInt(st.nextToken());
        sub=Integer.parseInt(st.nextToken());
        mul=Integer.parseInt(st.nextToken());
        div=Integer.parseInt(st.nextToken());
 
        DFS(1,arr[0]);
        System.out.println(max);
        System.out.println(min);
 
    }
 
 
 
}
 
cs

 

그래프 + 백트래킹으로 풀면 됐다.

생각보다 쉬운 문제였다. 아 그리고 else if가 아니라 if 써줘야 한다. 이거 때문에 답이 자꾸 잘못 나왔다.

728x90
반응형

댓글