알고리즘
백준 2579번 계단 오르기 (JAVA)
박카스마시며코딩
2023. 12. 13. 23:19
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;
public class BOJ_2579_2 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] score = new int[n];
int[][] dp = new int[n][3];
for(int i = 0 ; i < n ; i++){
Arrays.fill(dp[i],NOT_VALID);
score[i] = Integer.parseInt(br.readLine());
}
int result = cal(n-1,score,1,n,dp);
System.out.println(result);
}
private static final int NOT_VALID = -1;
private static int cal(int depth, int[] score, int cnt,int n,int[][] dp) {
if(depth < 0){
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,score,cnt+1,n,dp) + score[depth]);
}
result = Math.max(result,cal(depth-2,score,1,n,dp) + score[depth]);
dp[depth][cnt] = result;
return result;
}
}