JAVA/Coding Test

[JAVA] 백준 2688 줄어들지 않아_DP

오늘도개발 2024. 6. 26. 20:27

문제 :

https://www.acmicpc.net/problem/2688

 

 

접근 : 

 

 - n = 1,  dp[1] = 10, before = {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}

 

 - n = 2, dp[2] = 10 - 0 + 10 - 1 + 9 - 1 + · · · + 2 - 1 , before = {0, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}

 

 - n = 3, dp[3] = 55 - 0 + 55 - 10 + 45 - 9 + · · · + 2 - 1, before = {0, 55, 45,  36, 28, 21, 15, 10, 6, 3, 1}

 

즉 dp[n] = dp[n-1] - before[0] + (dp[n-1] - before[0]) - before[1] + ( (dp[n-1] - before[0]) - before[1]) - before[2] + · · ·   

 

dp[n] 을 계산하기 위해 dp[n-1]을 더한 후, before[0] 부터 before[9] 까지 이전의 결과값에 before[i] 값을 빼면서 더한다.

 

 

코드  :

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

public class Main {
    public static class DataTable{
        private long[] dp;
        private long[] before;
        private int next_num;
        public DataTable(){
            this.dp = new long[1001];
            this.dp[1] = 10;
            this.before = new long[]{ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
            next_num = 2;

        }
        public void updateTable(int n){
            long temp = 0;
            long temp_before = this.dp[n-1];
            long[] temp_sum = new long[11];

            for( int i = 0 ; i < 10 ; i++){
                temp_before -= this.before[i];
                temp += temp_before;
                temp_sum[i+1] = temp_before;
            }
            this.dp[n] = temp;
            this.before = temp_sum;
        }
        public long getN(int n){
            while(this.next_num <= n) this.updateTable(this.next_num++);
            return this.dp[n];
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();

        int t = Integer.parseInt(br.readLine());
        DataTable dt = new DataTable();

        for (int i=0 ; i < t ; i++) sb.append(String.format("%d%n", dt.getN(Integer.parseInt(br.readLine()))));

        System.out.println(sb);
        br.close();
    }
}