알고리즘
백준 2579번 계단 오르기 (JAVA)
박카스마시며코딩
2023. 7. 7. 23:17
https://www.acmicpc.net/problem/2579
2579번: 계단 오르기
계단 오르기 게임은 계단 아래 시작점부터 계단 꼭대기에 위치한 도착점까지 가는 게임이다. <그림 1>과 같이 각각의 계단에는 일정한 점수가 쓰여 있는데 계단을 밟으면 그 계단에 쓰여 있는 점
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_2579 {
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+1];
int[][] dp = new int[n+1][3];
for(int i = 0 ; i <= n ; i++){
Arrays.fill(dp[i],NOT_VALID);
if(i == 0){
continue;
}
input[i] = stoi.apply(br.readLine());
}
int result = cal(n,1,input,n,dp);
System.out.println(result);
}
private static int cal(int depth, int cnt, int[] input, int n,int[][]dp ) {
if(dp[depth][cnt] != NOT_VALID){
return dp[depth][cnt];
}
int result = 0;
if(cnt + 1 < 3 && depth -1 > 0){
result = Math.max(result,cal(depth-1,cnt+1,input,n,dp));
}
if(depth -2 > 0){
result = Math.max(result,cal(depth-2,1,input,n,dp));
}
result += input[depth];
dp[depth][cnt] = result;
return result;
}
}