CS/알고리즘_삼성 SW 역량 테스트 기출 문제

삼성 SW 역량 테스트 기출 문제 : 연산자 끼워넣기

Jedy_Kim 2021. 10. 13. 18:50
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
import java.util.*;
import java.io.*;
 
public class Main{ 
  
  static int MAX = Integer.MIN_VALUE; 
  static int MIN = Integer.MAX_VALUE;
  static int N; 
  static int[] number;
  static int[] operArr = new int[4];
  
  static void getResult(int num, int idx) { 
    if(idx == N) {      
      MAX = Math.max(MAX, num);
      MIN = Math.min(MIN, num);
      return;
    }
    
    for(int i=0; i<4; i++) {
      
      // 연산자 개수가 1개 이상인 경우
      if(operArr[i] > 0) {
        // 해당 연산자를 1감소시킨다.
        operArr[i]--;
        
        switch(i) {
          
        case 0: getResult(num + number[idx], idx + 1); break;
        case 1: getResult(num - number[idx], idx + 1); break;
        case 2: getResult(num * number[idx], idx + 1); break;
        case 3: getResult(num / number[idx], idx + 1); break;
            
        }
        
        // 재귀호출이 종료되면 다시 해당 연산자 개수를 복구한다.
        operArr[i]++;
      }
      
    }
    
  }
  
  // main
  public static void main(String[] args) throws Exception {
    
    BufferedWriter bw  = new BufferedWriter(new OutputStreamWriter(System.out));
    BufferedReader br  = new BufferedReader(new InputStreamReader(System.in)); 
    
    N = Integer.parseInt(br.readLine());
    number = new int[N];
    
    // 숫자
    StringTokenizer st = new StringTokenizer(br.readLine()); 
    for(int i=0; i<N; ++i) number[i] = Integer.parseInt(st.nextToken());
    
    // 연산자 입력
    st= new StringTokenizer(br.readLine());
    for(int i=0; i<4++i) operArr[i] = Integer.parseInt(st.nextToken());
    
    getResult(number[0], 1);
    
    bw.write(String.valueOf(MAX));
    bw.newLine();
    bw.write(String.valueOf(MIN));
    
    br.close();
    bw.flush();
    bw.close();
  } 
}
 
cs

 

반응형