[코드그루] 126. 백준 15658번 : 연산자 끼워넣기 (2)

2025. 1. 23. 19:50·코딩테스트

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

// 주어진 연산자 모두 사용해서 최댓값/최솟값 구하기
public class Main {
    static int n;
    static int[] a;
    static int[] op;
    static int max = Integer.MIN_VALUE;
    static int min = Integer.MAX_VALUE;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        n = Integer.parseInt(br.readLine());
        a = new int[n];
        StringTokenizer st = new StringTokenizer(br.readLine());
        for (int i=0; i < n; i++) {
            a[i] = Integer.parseInt(st.nextToken());
        }
        op = new int[4];
        st = new StringTokenizer(br.readLine());
        for (int i=0; i < 4; i++) {
            op[i] = Integer.parseInt(st.nextToken());
        }
        dfs(1, a[0]);
        System.out.println(max);
        System.out.println(min);
    }

    public static void dfs(int depth, int cur) {
        if (depth == n) {
            max = Math.max(max, cur);
            min = Math.min(min, cur);
            return;
        }
        for (int i=0; i < 4; i++) {
            if (op[i] > 0) {    // 사용한 연산자 제거
                op[i]--;
                if (i == 0) { // +
                    dfs(depth + 1, cur + a[depth]);
                } else if (i == 1) { // -
                    dfs(depth + 1, cur - a[depth]);
                } else if (i == 2) { // *
                    dfs(depth + 1, cur * a[depth]);
                } else if (i == 3) { // /
                    dfs(depth + 1, divide(cur, a[depth]));
                }
                op[i]++;    // 복구
            }
        }
    }

    private static int divide(int cur, int a) {
        if (cur < 0) {  // 분모가 음수라면
            return -(-cur / a);
        } else {
            return cur / a;
        }
    }
}

728x90

'코딩테스트' 카테고리의 다른 글

[코드그루] 128. 백준 31848번 : 엉성한 도토리 분류기  (1) 2025.01.29
[코드그루] 127. 백준 15903번 : 카드 합체 놀이  (1) 2025.01.29
[코드그루] 125. 백준 2792번 : 보석 상자  (2) 2025.01.22
[코드그루] 124. 백준 3216번 : 다운로드  (1) 2025.01.21
[코드그루] 123. 백준 2573번 : 빙산  (1) 2025.01.21
'코딩테스트' 카테고리의 다른 글
  • [코드그루] 128. 백준 31848번 : 엉성한 도토리 분류기
  • [코드그루] 127. 백준 15903번 : 카드 합체 놀이
  • [코드그루] 125. 백준 2792번 : 보석 상자
  • [코드그루] 124. 백준 3216번 : 다운로드
hnajeahi
hnajeahi
개발 스터딩
  • hnajeahi
    hnajeahi-hub
    hnajeahi
  • 전체
    오늘
    어제
    • 전체보기 (95)
      • 개발일기 (2)
      • 코딩테스트 (64)
      • TIL (29)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

    • 블로그 이사왔음!
  • 인기 글

  • 태그

    해시
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
hnajeahi
[코드그루] 126. 백준 15658번 : 연산자 끼워넣기 (2)
상단으로

티스토리툴바