본문 바로가기

알고리즘/재귀

[JAVA] 백준 16198번: 에너지 모으기

문제

N개의 에너지 구슬이 일렬로 놓여져 있고, 에너지 구슬을 이용해서 에너지를 모으려고 한다.

i번째 에너지 구슬의 무게는 Wi이고, 에너지를 모으는 방법은 다음과 같으며, 반복해서 사용할 수 있다.

  1. 에너지 구슬 하나를 고른다. 고른 에너지 구슬의 번호를 x라고 한다. 단, 첫 번째와 마지막 에너지 구슬은 고를 수 없다.
  2. x번째 에너지 구슬을 제거한다.
  3. Wx-1 × Wx+1의 에너지를 모을 수 있다.
  4. N을 1 감소시키고, 에너지 구슬을 1번부터 N번까지로 다시 번호를 매긴다. 번호는 첫 구슬이 1번, 다음 구슬이 2번, ... 과 같이 매겨야 한다.

N과 에너지 구슬의 무게가 주어졌을 때, 모을 수 있는 에너지 양의 최댓값을 구하는 프로그램을 작성하시오.

입력

첫째 줄에 에너지 구슬의 개수 N(3 ≤ N ≤ 10)이 주어진다.

둘째 줄에는 에너지 구슬의 무게 W1, W2, ..., WN을 공백으로 구분해 주어진다. (1 ≤ Wi ≤ 1,000)

출력

첫째 줄에 모을 수 있는 에너지의 최댓값을 출력한다.

 

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    static int n;
    static boolean[] visit;
    static int[] info;
    static int[] dfsAry;
    static int res;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        visit = new boolean[n];
        info = new int[n];
        dfsAry = new int[n - 2];
        for (int i = 0; i < n; i++) {
            info[i] = sc.nextInt();
        }

        dfs(0);
        System.out.println(res);
    }

    static void dfs(int index) {
        if (index == n - 2) {
            findMaxWeight(dfsAry);
            return;
        }
        for (int i = 1; i < n - 1; i++) {
            if (!visit[i]) {
                visit[i] = true;
                dfsAry[index] = i;
                dfs(index + 1);
                visit[i] = false;
            }
        }
    }

    static void findMaxWeight(int[] weightAry) {
        boolean[] check = new boolean[n];
        int tempRes = 0;

        for (int i = 0; i < weightAry.length; i++) {
            int target = weightAry[i];
            int leftTarget = target - 1;
            int rightTarget = target + 1;

            while (check[leftTarget]) {
                leftTarget--;
            }
            while (check[rightTarget]) {
                rightTarget++;
            }

            if (!check[leftTarget] && !check[rightTarget]) {
                check[target] = true;
                tempRes += info[leftTarget] * info[rightTarget];
                if (rightTarget == n - 1) {
                    check[rightTarget] = false;
                }
                if (leftTarget == 0) {
                    check[leftTarget] = false;
                }
            }
        }
        res = Math.max(res, tempRes);
    }
}

 

 

'알고리즘 > 재귀' 카테고리의 다른 글

백준 14501번: 퇴사  (0) 2021.07.31
[JAVA] 백준 14500번: 테트로미노  (0) 2021.07.22
[JAVA] 백준 1182번: 부분수열의 합  (0) 2021.07.21
[JAVA] 백준 6603번: 로또  (0) 2021.07.21