๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm/๋ฐฑ์ค€

[๋ฐฑ์ค€] #14501 ํ‡ด์‚ฌ (Python)

ํ‡ด์‚ฌ

๋ฌธ์ œ

ํ‡ด์‚ฌ๋ฅผ ์ง„ํ–‰ํ–‰ํ•˜๋ ค ํ•˜๋Š”๋Š”๋ฐ N+1์ผ ์งธ ๋˜๋Š”๋‚  ํ‡ด์‚ฌ๋ฅผ ํ•˜๊ธฐ ์œ„ํ•ด์„œ N์ผ ๋™์•ˆ ๋งŽ์€ ์ƒ๋‹ด์„ ํ•˜๋ ค๊ณ  ํ•œ๋‹ค.

์ƒ๋‹ด์„ ์™„๋ฃŒํ•˜๋Š”๋ฐ ๊ฑธ๋ฆฌ๋Š” ์‹œ๊ฐ„ T์™€ ์ƒ๋‹ด์„ ํ–ˆ์„ ๋•Œ ๋ฐ›์„ ์ˆ˜ ์žˆ๋Š” ๊ธˆ์•ก P๋ฅผ ๋ณด๊ณ , ํ‡ด์‚ฌ ์ „๊นŒ์ง€ ์ตœ๋Œ€ ์ˆ˜์ต์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

์˜ˆ์ œ

  1์ผ 2์ผ 3์ผ 4์ผ 5์ผ 6์ผ 7์ผ
Ti 3 5 1 1 2 4 2
Pi 10 20 10 20 15 40 200
์ž…๋ ฅ
7
3 10
5 20
1 10
1 20
2 15
4 40
2 200

์ถœ๋ ฅ
45

๋ฌธ์ œ ํ’€์ด ์ „๋žต

day 0 1 2 3 4 5 6
Ti 3 5 1 1 2 3 2
Pi 10 20 10 20 15 40 200

day๋Š” 0~n-1, ํ‡ด์‚ฌ์ผ n
dp ๋ฐฉ์‹์œผ๋กœ ํ‘ผ๋‹ค

  • dp[day] = max(dp[day+1],dp[day+T[day]]+P[day])
  • day์—์„œ ์‹œ์ž‘ํ•ด์„œ ํ‡ด์‚ฌ์ผ๊นŒ์ง€์˜ ์ˆ˜์ต์˜ ์ตœ๋Œ“๊ฐ’์„ dp[day]์— ์ €์žฅ
    ex) dp[0]์—๋Š” 0์ผ๋ถ€ํ„ฐ ํ‡ด์‚ฌํ•  ๋•Œ๊นŒ์ง€์˜ ์ตœ๋Œ“๊ฐ’์„ ์ €์žฅ

dp[day]์—๋Š” ๋‘ ๊ฐ€์ง€ ์ค‘์—์„œ ์ตœ๋Œ“๊ฐ’์„ ์ €์žฅ

  • ์˜ค๋Š˜์˜ ์Šค์ผ€์ค„์„ ์•ˆ ํ•˜๋Š” ๊ฒฝ์šฐ
    dp[day+1] : ์˜ค๋Š˜์˜ ์Šค์ผ€์ค„์„ ์•ˆํ•˜๋Š” ๊ฒฝ์šฐ๋Š” ๋‚ ์งœ๋ฅผ ํ•˜๋‚˜ ๋„˜๊ธฐ๋ฉด ๋จ
  • ์˜ค๋Š˜์˜ ์Šค์ผ€์ค„์„ ํ•˜๋Š” ๊ฒฝ์šฐ
    dp[day +T[day]]+P[day] : day[0]์˜ ์Šค์ผ€์ค„์„ ํ–ˆ๋‹ค๋ฉด 0 ๋”ํ•˜๊ธฐ day[0]์„ ์†Œํ™”ํ•˜๋Š”๋ฐ ๊ฑธ๋ฆฌ๋Š” ๊ธฐ๊ฐ„์ธ T[day]๋ฅผ ๋”ํ•ด์ฃผ๊ณ , ์Šค์ผ€์ค„์„ ์†Œํ™”ํ–ˆ๊ธฐ ๋•Œ๋ฌธ์—, day[0]์—์„œ ์ค„ ์ˆ˜ ์žˆ๋Š” ๊ธˆ์•ก์ธ P[day]๋ฅผ ๋”ํ•ด์ค€๋‹ค.

dp[day] = max(dp[day+1],dp[day+T[day]]+P[day])

solve(0) = max(solve(1),solve(3)+10) = 45
solve(1) = max(solve(2),solve(6)+20) = 45
solve(2) = max(solve(3),solve(3)+10) = 45
solve(3) = max(solve(4),solve(4)+20) = 35
solve(4) = max(solve(5),solve(6)+15) = 15
solve(5) = max(solve(6),solve(8)+40) = 0
solve(6) = max(solve(7),solve(8)+200) = 0
solve(7) = 0
solve(8) = -๋ฌดํ•œ๋Œ€
solve(8)๋ถ€ํ„ฐ๋Š” 9์ผ์— ํ‡ด์‚ฌํ•˜๋Š”๊ฒŒ ๋˜์–ด๋ฒ„๋ฆผ

Results

Version Memory Time(ms) info
solution1.py 28776KB 64ms Baseline

Solution 1

def solve(t,p):
    max_pay = 0 #์ง€๊ธˆ๊นŒ์ง€ ์ตœ๋Œ€ํŽ˜์ด
    for day in range(n):
        max_pay = max(max_pay,dp[day])
        if day+t[day] > n:
            continue
        dp[day+t[day]] = max(dp[day+t[day]],max_pay+p[day])
        #max(์ผ์„ ์•ˆ ํ•˜๊ณ  ๋„˜์–ด๊ฐˆ ๊ฒฝ์šฐ ํŽ˜์ด,ํ˜„์žฌ day๊นŒ์ง€์™€์„œ ๋ฒŒ์€ ๋ˆ์˜ ์ตœ๋Œ“๊ฐ’ + ํ˜„์žฌ ์ผ์„ ํ•  ๊ฒฝ์šฐ ํŽ˜์ด)

    print(max(dp))

if __name__ == "__main__":
    n = int(input())
    t,p = [0]*n,[0]*n
    dp = [0]*(n+1)

    for i in range(n):
        t[i], p[i] = map(int, input().split())

    solve(t,p)