https://www.acmicpc.net/problem/2579
2579번: 계단 오르기
계단 오르기 게임은 계단 아래 시작점부터 계단 꼭대기에 위치한 도착점까지 가는 게임이다. <그림 1>과 같이 각각의 계단에는 일정한 점수가 쓰여 있는데 계단을 밟으면 그 계단에 쓰여 있는 점
www.acmicpc.net
동적 계획법 문제이다.
현재 인덱스 i에 대해 두 칸 전(i-2) 의 '메모이제이션 값' 과 첫 칸 전(i-1)의 값 + 세번째 칸 전 (i-3)의 '메모이제이션 값' 중 큰 값을 현재 i 계단의 값과 합하여 DP 배열에 저장해주면 된다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class B_2579 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int[] stairs = new int[N+1];
int[] dp = new int[N+1];
for(int i = 1; i <= N; i++){
stairs[i] = Integer.parseInt(br.readLine());
}
dp[1] = stairs[1];
if(N >= 2){
dp[2] = stairs[1] + stairs[2];
}
for(int i = 3; i <= N; i++){
dp[i] = Math.max(dp[i-2], dp[i-3] + stairs[i-1]) + stairs[i];
}
System.out.println(dp[N]);
}
}
처음에 이해가 잘 되지 않아 직접 하나씩 옮겨봤다.
참고 블로그 :
https://st-lab.tistory.com/132
'알고리즘' 카테고리의 다른 글
백준_8958_OX퀴즈 (0) | 2023.07.28 |
---|---|
백준_2798_블랙잭 (0) | 2023.07.28 |
백준 - 1676 - 팩토리얼 0의 개수 (0) | 2023.03.30 |
백준 - 1463 - 1로 만들기 (0) | 2023.03.27 |
백준 - 1302 - 베스트셀러 (0) | 2023.03.27 |