๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Coding Test/Algorithms

[Baekjoon] 9461.ํŒŒ๋„๋ฐ˜ ์ˆ˜์—ด/Java - Silver3

by The Future Engineer, Lucy 2024. 10. 15.
728x90
๋ฐ˜์‘ํ˜•

โ“๋ฌธ์ œ

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

์„ฑ๋Šฅ ์š”์•ฝ

๋ฉ”๋ชจ๋ฆฌ: 14232 KB, ์‹œ๊ฐ„: 100 ms

๋ถ„๋ฅ˜

๋‹ค์ด๋‚˜๋ฏน ํ”„๋กœ๊ทธ๋ž˜๋ฐ, ์ˆ˜ํ•™

๋ฌธ์ œ ์„ค๋ช…

์˜ค๋ฅธ์ชฝ ๊ทธ๋ฆผ๊ณผ ๊ฐ™์ด ์‚ผ๊ฐํ˜•์ด ๋‚˜์„  ๋ชจ์–‘์œผ๋กœ ๋†“์—ฌ์ ธ ์žˆ๋‹ค. ์ฒซ ์‚ผ๊ฐํ˜•์€ ์ •์‚ผ๊ฐํ˜•์œผ๋กœ ๋ณ€์˜ ๊ธธ์ด๋Š” 1์ด๋‹ค. ๊ทธ ๋‹ค์Œ์—๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ณผ์ •์œผ๋กœ ์ •์‚ผ๊ฐํ˜•์„ ๊ณ„์† ์ถ”๊ฐ€ํ•œ๋‹ค. ๋‚˜์„ ์—์„œ ๊ฐ€์žฅ ๊ธด ๋ณ€์˜ ๊ธธ์ด๋ฅผ k๋ผ ํ–ˆ์„ ๋•Œ, ๊ทธ ๋ณ€์— ๊ธธ์ด๊ฐ€ k์ธ ์ •์‚ผ๊ฐํ˜•์„ ์ถ”๊ฐ€ํ•œ๋‹ค.
ํŒŒ๋„๋ฐ˜ ์ˆ˜์—ด P(N)์€ ๋‚˜์„ ์— ์žˆ๋Š” ์ •์‚ผ๊ฐํ˜•์˜ ๋ณ€์˜ ๊ธธ์ด์ด๋‹ค. P(1)๋ถ€ํ„ฐ P(10)๊นŒ์ง€ ์ฒซ 10๊ฐœ ์ˆซ์ž๋Š” 1, 1, 1, 2, 2, 3, 4, 5, 7, 9์ด๋‹ค.
N์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, P(N)์„ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

โœ๐Ÿปํ’€์ด

์ฒซ ์‚ผ๊ฐํ˜•์€ ๋ณ€์˜ ๊ธธ์ด๊ฐ€ 1์ธ ์ •์‚ผ๊ฐํ˜•. ์ •์‚ผ๊ฐํ˜•์„ ๊ณ„์† ์ถ”๊ฐ€.
3๋ฒˆ์งธ ์ •์‚ผ๊ฐํ˜• ์ถ”๊ฐ€ ํ›„ ๊ฐ€์žฅ ๊ธด ๋‚˜์„ ์˜ ๊ธธ์ด๋Š” 2์ด๋ฏ€๋กœ ๋ณ€์˜ ๊ธธ์ด๊ฐ€ 2์ธ ์ •์‚ผ๊ฐํ˜•์„ ์ถ”๊ฐ€.
๋‚˜์„ ์˜ ๊ธธ์ด๊ฐ€ ๊ฐ€์žฅ ๊ธด ๋ณ€์— ์ •์‚ผ๊ฐํ˜•์„ ๊ณ„์† ์ถ”๊ฐ€.
5๋ฒˆ์งธ ์ •์‚ผ๊ฐํ˜•๋ถ€ํ„ฐ dp[i] = dp[i - 1] + dp[i - 5] ๋ผ๋Š” ๊ทœ์น™์„ ์ฐพ์„ ์ˆ˜ ์žˆ์Œ.
์ •์ˆ˜์˜ ๊ธธ์ด๋ฅผ ๊ณ ๋ คํ•˜์—ฌ dp๋Š” int๊ฐ€ ์•„๋‹Œ long์œผ๋กœ ์„ ์–ธ.

๐Ÿ’ป์ฝ”๋“œ

import java.io.*;

public class Main {

    static int n;

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int T = Integer.parseInt(br.readLine());

        for (int i = 0; i < T; i++) {
            n = Integer.parseInt(br.readLine());

            long[] dp = new long[101];
            dp[0] = 0;
            dp[1] = 1;
            dp[2] = 1;
            dp[3] = 1;
            dp[4] = 2;

            for(int j = 5; j <= n; j++){
                dp[j] = dp[j - 1] + dp[j - 5];
            }

            System.out.println(dp[n]);
        }
    }
}
728x90
๋ฐ˜์‘ํ˜•