알고리즘

백준 21317번 징검다리 건너기 (JAVA)

박카스마시며코딩 2024. 1. 2. 16:38

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

 

21317번: 징검다리 건너기

산삼을 얻기 위해 필요한 영재의 최소 에너지를 출력한다.

www.acmicpc.net

 

저는 DP를 이용해 문제를 풀었습니다.

DP를 이용해 이전에 계산한 것을 다시 계산하지 않도록 하여 시간안에 동작하도록 구현하였습니다.

 

package BOJ.dp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class BOJ_21317_2 {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        int[][] energy = new int[n][2];
        int[][] dp = new int[n][2];
        for(int i = 0 ; i < n-1 ; i++){
            Arrays.fill(dp[i],NOT_VALID);
            StringTokenizer st = new StringTokenizer(br.readLine());
            for(int j = 0 ; j < 2; j++){
                energy[i][j] = Integer.parseInt(st.nextToken());
            }
        }
        int k = Integer.parseInt(br.readLine());
        int result = cal(0,NOT_USED,energy,k,n-1,dp);
        System.out.println(result);
    }
    private static final int NOT_USED = 0;
    private static final int NOT_VALID = -1;
    private static final int USED = 1;
    private static final int INF = 987654321; // 5000 * 20
    private static int cal(int depth, int used, int[][] energy, int k, int n,int[][] dp) {
        if(depth == n){
            return 0;
        }
        if(dp[depth][used] != NOT_VALID){
            return dp[depth][used];
        }
        int result = INF;
        for(int i = 0 ; i < 2; i++){
            if(depth+i+1 <= n){
                result = Math.min(result,cal(depth+i+1,used,energy,k,n,dp) + energy[depth][i]);
            }
        }
        if(depth+3 <= n && used == NOT_USED){
            result = Math.min(result,cal(depth+3,USED,energy,k,n,dp) + k);
        }
        dp[depth][used] = result;
        return result;
    }
}

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

백준 21921번 블로그 (JAVA)  (0) 2024.01.04
백준 2792번 보석 상자 (JAVA)  (0) 2024.01.03
백준 16197번 두 동전 (JAVA)  (1) 2024.01.01
백준 19621번 회의실 배정 2 (JAVA)  (0) 2023.12.31
백준 1890번 점프 (JAVA)  (0) 2023.12.30