1 minute read

๐Ÿ“Œ ๋‚œ์ด๋„

๐Ÿฅ‡ Gold 5


๐Ÿ“Œ ๋ฌธ์ œ

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


image

image


๐Ÿ“Œ ํ’€์ด

์–ด์ œ DP๋ฌธ์ œ์— ์—„์ฒญ ๊ณ ๋ฏผ์„ ํ•˜๊ณ , DP ๋ฌธ์ œ๊ฐ€ ์–ด๋–ค ํ˜•์‹์ธ์ง€ ์–ด๋–ค ๋ฐฉ๋ฒ•์œผ๋กœ ์ ‘๊ทผ์„ ํ•ด์•ผ ํ•˜๋Š”์ง€, ๊นจ๋‹ฌ์Œ์„ ์–ป์–ด์„œ ๊ทธ๋Ÿฐ๊ฐ€, ๊ณจ๋“œ๋ฌธ์ œ์ž„์—๋„ ๋ถˆ๊ตฌํ•˜๊ณ  ๋งค์šฐ ์‰ฝ๊ฒŒ ํ’€๋ ธ๋‹ค.

์ผ๋‹จ ๋‚ ์งœ์™€ ๋ˆ์„ arr์— ์ง‘์–ด๋„ฃ์—ˆ๊ณ , dp๋Š” 0์œผ๋กœ ์ „๋ถ€ ์ดˆ๊ธฐํ™” ํ•ด์ฃผ์—ˆ๋‹ค.

image

for๋ฌธ์œผ๋กœ ์ฒ˜์Œ๋ถ€ํ„ฐ ๋๊นŒ์ง€ ๋Œ๋ฆฐ๋‹ค๊ณ  ํ•˜์ž, ์ด๋•Œ n๋ฒˆ์งธ์ผ๋•Œ, dp[n]์€ ์ง€๊ธˆ๊นŒ์ง€ ๋“ค์–ด์˜จ dp๊ฐ’(์ดํ›„ ์„ค๋ช…)๊ณผ ์ด์ „ ๊ฐ’์„ ๋น„๊ตํ•˜์—ฌ, ๋” ํฐ ๊ฐ’์„ ๋„ฃ๋Š”๋‹ค.
์ดํ›„ ๊ฐ€์žฅ ์ค‘์š”ํ•œ ๋ถ€๋ถ„์ธ๋ฐ, arr[n][0](์ƒ๋‹ด์— ๊ฑธ๋ฆฌ๋Š” ์‹œ๊ฐ„) + ํ˜„์žฌ Index์˜ ์ฃผ์†Œ๊ฐ’์— ์žˆ๋Š” dp๊ฐ’์— ํ˜„์žฌ dp[n] + arr[n][1]๋ฅผ Math.max๋กœ ๋” ํฐ ๊ฐ’์œผ๋กœ ์ดˆ๊ธฐํ™” ํ•ด์ค€๋‹ค.
์ด๋Ÿฐ์‹์œผ๋กœ ๋ฐ˜๋ณต๋ฌธ์„ ๋Œ๋ฆฌ๋ฉด ๊ฒฐ๊ตญ ๊ฐ dp์— ์žˆ๋Š” ๊ฐ’์€ ํ•ญ์ƒ ์ตœ๋Œ€๊ฐ’์ด ๋œ๋‹ค.

DP ๋ฌธ์ œ๋ฅผ ํ’€๋ฉด์„œ ๋Š๋‚€์ ์€ ์–ด๋–ป๊ฒŒ ํ•ด์•ผ์ง€ dp์— ์žˆ๋Š” ๊ฐ’์ด ํ•ญ์ƒ ๊ทธ ์ง€์ ์˜ ์ตœ๋Œ€๊ฐ’/์ตœ์†Œ๊ฐ’์ด ๋  ์ˆ˜ ์žˆ๋Š”์ง€์— ๋Œ€ํ•ด ๊ณ ๋ฏผํ•˜๊ณ , ๊ทธ์— ๋Œ€ํ•œ ์ ํ™”์‹์„ ์ฐพ์•„๋‚ด๋Š” ๊ฒƒ์ด ์ค‘์š”ํ•˜๋‹ค๋Š” ๊ฒƒ์„ ๋Š๊ผ‡๋‹ค.

๋ฌธ์ œ๋ฅผ ํ’€๋ฉด ํ’€์ˆ˜๋ก ์‹ค๋ ฅ์ด ํ™•ํ™• ๋Š๋Š” ๋Š๋‚Œ์ด๋ผ ์š”์ฆ˜ ๊ณต๋ถ€ํ•˜๋Š” ๋ง›์ด ๋‚œ๋‹ค. ๐Ÿ˜Ž


๐Ÿ“Œ Code

package DP;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;

public class N15486 {
    public static int[][] arr;
    public static int[] dp;
    static int target;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        target = Integer.parseInt(br.readLine());
        arr = new int[target + 2][2];
        dp = new int[target + 2];

        Arrays.fill(dp, 0);

        StringTokenizer st;
        arr[0][0] = 0;
        arr[0][1] = 0;
        for (int i = 1; i < target + 1; i++) {
            st = new StringTokenizer(br.readLine());
            arr[i][0] = Integer.parseInt(st.nextToken());
            arr[i][1] = Integer.parseInt(st.nextToken());
        }
        for (int i = 1; i < target + 2; i++) {
            MakeDP(i);
        }

        System.out.println(dp[target + 1]);
    }

    public static void MakeDP(int index) {
        dp[index] = Math.max(dp[index], dp[index - 1]);
        if (index + arr[index][0] <= target + 1) {
            dp[index + arr[index][0]] = Math.max(arr[index][1] + dp[index], dp[index + arr[index][0]]);
        }
    }
}

package (์ด๋ฆ„); ๋ฅผ ๋•Œ๊ณ , class ์ด๋ฆ„์„ Main์œผ๋กœ ๋ณ€๊ฒฝํ•˜๋ฉด ๋œ๋‹ค.



๊ฐœ์ธ ๊ณต๋ถ€ ๊ธฐ๋ก์šฉ ๋ธ”๋กœ๊ทธ์ž…๋‹ˆ๋‹ค.
ํ‹€๋ฆฌ๊ฑฐ๋‚˜ ์˜ค๋ฅ˜๊ฐ€ ์žˆ์„ ๊ฒฝ์šฐ ์ œ๋ณดํ•ด์ฃผ์‹œ๋ฉด ๊ฐ์‚ฌํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.๐Ÿ˜