0x10 - DP : BOJ 2579 계단오르기기

Jieun·2024년 6월 16일
0

코테

목록 보기
9/18

https://github.com/encrypted-def/basic-algo-lecture/blob/master/workbook/0x10.md
이 문제집을 푸는 중입니다

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        int[] s = new int[305];
        for (int i = 1; i <= n; i++) s[i] = Integer.parseInt(br.readLine());

        //1. 테이블정의
        // d[i][2] : 계단을 밟았을 때 점수합의 최댓값, 2차원은 연속해서 n번 밟았을 때
        int[][] d = new int[305][2];

        //2. 초기값 설정
        d[1][0] = s[1]; d[1][1] = s[1];
        d[2][0] = s[2]; d[2][1] = s[1]+s[2];

        //3. 점화식 찾기
        //d[3][0] = Math.max(d[1][0], d[1][1])+s[3];
        //d[3][1] = d[2][0]+s[3];
        for (int i = 3; i <= n; i++) {
            d[i][0] = Math.max(d[i-2][0], d[i-2][1])+s[i];
            d[i][1] = d[i-1][0]+s[i];
        }

        System.out.println(Math.max(d[n][0], d[n][1]));
    }

}
  1. 테이블 정의
    계단을 밟았을 때 점수합의 최댓값
    연속해서 밟는 경우의 수를 표현하기 위해 2차원배열(BFS에서 벽부수기 처럼)
    d[i][0] : i번째 계단을 연속 0번째로 밟은 경우
    d[i][1] : i번째 계단을 연속 1번째로 밟은 경우

  2. 초기값 설정
    d[1], d[2] -> d[3] 구현할 수 있으므로 d[1], d[2] 설정

  3. 점화식 찾기
    d[i][0] : 연속 0번째이므로 d[i-2]에서 올라오는 경우,
    d[i-2][0] - d[i-2][1] 중 더 큰 값 + 계단의 s[i]

d[i][1] : 연속 1번째이므로 d[i-1]에서 올라오는 경우,
d[i-1][1]에서는 더 연속해서 올라올 수 없으므로 (연속횟수 제한조건)
d[i-1][0] + 계단의 s[i]

  1. 결과 n
    d[n][0] - d[n][1]중 최댓값 출력

0개의 댓글