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;
}
}
'알고리즘' 카테고리의 다른 글
백준 8911번 거북이 (JAVA) (1) | 2023.12.15 |
---|---|
백준 11048번 이동하기 (JAVA) (0) | 2023.12.14 |
백준 7795번 먹을 것인가 먹힐 것인가 (JAVA) (0) | 2023.12.12 |
백준 1654번 랜선 자르기 (JAVA) (1) | 2023.12.11 |
백준 1914번 하노이 탑 (JAVA) (1) | 2023.12.10 |