백준 2302번 자바 : 극장 좌석

Rena·2024년 2월 4일
0

알고리즘 문제풀이

목록 보기
42/45

다이나믹 프로그래밍 : dp 배열의 크기, ArrayIndexOutOfBounds 유의!

n번 자리를 이동하지 않을 경우 dp[n-1]
n번 자리를 이동할 경우 dp[n-2]

dp[n] = dp[n-1] + dp[n-2]

ArrayIndexOutOfBounds가 계속 났었는데 그 이유는
N이 2보다 작을 수도 있는데 dp의 크기를 N+1로 해놓고 dp[0],dp[1],dp[2]에 대해 초기화를 했기 때문이다.

N이 1이라면, dp[2]이 생성되고, dp[0],dp[1]만 접근 가능함

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.*;

public class Main { 

    static int N,M;
    static int[] dp = new int[41];
    static int[] vip = new int[41];

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        N = sc.nextInt();

        dp[0] = 1;
        dp[1] = 1;
        dp[2] = 2;

        for(int i=3; i<=N; i++) {
            dp[i] = dp[i-1] + dp[i-2];
        }

        M = sc.nextInt();
        for(int i=0; i<M; i++) {
            vip[sc.nextInt()] = 1;
        }

        int answer = 1;
        int start = 0;
        for(int i=1; i<=N; i++) {
            if(vip[i]==1) {
                answer *= dp[start];
                start = 0;
                continue;
            }
            start++;
        }
        answer *= dp[start];

        System.out.println(answer);

    }


}
profile
일을 사랑하고 싶은 개발자

0개의 댓글