알고리즘

백준 23029번 시식 코너는 나의 것(JAVA)

박카스마시며코딩 2023. 9. 15. 16:33

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

 

23029번: 시식 코너는 나의 것

첫째 줄에 시식코너의 개수 N이 주어진다(1 ≤ N ≤ 100,000) 둘째 줄부터 N+1번째 줄까지 각 시식코너에서 제공하는 음식의 개수가 순서대로 주어진다. 음식의 개수는 1,000이하의 음이 아닌 정수이

www.acmicpc.net

 

저는 DP를 이용해 문제를 해결하였습니다.

DP를 통해 이전에 계산한 값을 저장하였고, 모든 경우에서 가장 큰 값을 찾아 문제를 해결하였습니다.

 

package BOJ.dp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.function.Function;

public class BOJ_23029 {
    private static final int NOT_VALID = -1;
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Function<String,Integer> stoi = Integer::parseInt;
        int n = stoi.apply(br.readLine());
        int[] input = new int[n];
        int[][] dp = new int[n][3];
        for(int i = 0 ; i < n;  i++){
            Arrays.fill(dp[i],NOT_VALID);
            input[i] = stoi.apply(br.readLine());
        }
        int result = cal(0,0,input,n,dp);
        System.out.println(result);
    }

    private static int cal(int depth, int cnt, int[] input,int n,int[][] dp) {
        if(depth >= n){
            return 0;
        }
        if(dp[depth][cnt] != NOT_VALID){
            return dp[depth][cnt];
        }
        int result = 0;
        if(cnt < 2){
            result = Math.max(result,cal(depth+1,cnt+1,input,n,dp) + input[depth] / (cnt+1));
        }
        result = Math.max(result,cal(depth+1,0,input,n,dp));
        dp[depth][cnt] = result;
        return result;
    }
}

'알고리즘' 카테고리의 다른 글

백준 1812번 사탕 (JAVA)  (0) 2023.09.17
백준 1213번 팰린드룸 만들기 (JAVA)  (0) 2023.09.16
백준 1057번 토너먼트 (JAVA)  (0) 2023.09.14
백준 1080번 행렬 (JAVA)  (0) 2023.09.13
백준 2161번 카드1 (JAVA)  (0) 2023.09.12