์ƒˆ์†Œ์‹

๐Ÿงฎ PS

๋ฐฑ์ค€ (boj) ํŒŒ์ด์ฌ - 2579 ๋ฒˆ : ๊ณ„๋‹จ ์˜ค๋ฅด๊ธฐ

  • -

๋ฌธ์ œ๋งํฌ : https://www.acmicpc.net/problem/2579

 

2579๋ฒˆ: ๊ณ„๋‹จ ์˜ค๋ฅด๊ธฐ

๊ณ„๋‹จ ์˜ค๋ฅด๊ธฐ ๊ฒŒ์ž„์€ ๊ณ„๋‹จ ์•„๋ž˜ ์‹œ์ž‘์ ๋ถ€ํ„ฐ ๊ณ„๋‹จ ๊ผญ๋Œ€๊ธฐ์— ์œ„์น˜ํ•œ ๋„์ฐฉ์ ๊นŒ์ง€ ๊ฐ€๋Š” ๊ฒŒ์ž„์ด๋‹ค. <๊ทธ๋ฆผ 1>๊ณผ ๊ฐ™์ด ๊ฐ๊ฐ์˜ ๊ณ„๋‹จ์—๋Š” ์ผ์ •ํ•œ ์ ์ˆ˜๊ฐ€ ์“ฐ์—ฌ ์žˆ๋Š”๋ฐ ๊ณ„๋‹จ์„ ๋ฐŸ์œผ๋ฉด ๊ทธ ๊ณ„๋‹จ์— ์“ฐ์—ฌ ์žˆ๋Š” ์ ์ˆ˜๋ฅผ ์–ป๊ฒŒ ๋œ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด <๊ทธ๋ฆผ 2>์™€ ๊ฐ™์ด ์‹œ์ž‘์ ์—์„œ๋ถ€ํ„ฐ ์ฒซ ๋ฒˆ์งธ, ๋‘ ๋ฒˆ์งธ, ๋„ค ๋ฒˆ์งธ, ์—ฌ์„ฏ ๋ฒˆ์งธ ๊ณ„๋‹จ์„ ๋ฐŸ์•„ ๋„์ฐฉ์ ์— ๋„๋‹ฌํ•˜๋ฉด ์ด ์ ์ˆ˜๋Š” 10 + 20 + 25 + 20 = 75์ ์ด ๋œ๋‹ค. ๊ณ„๋‹จ ์˜ค๋ฅด๋Š” ๋ฐ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ทœ์น™์ด ์žˆ๋‹ค. ๊ณ„๋‹จ์€ ํ•œ ๋ฒˆ์— ํ•œ ๊ณ„๋‹จ์”ฉ

www.acmicpc.net

 

 

 

 

 

 

 


 

 

 

 

๋ฌธ์ œ ๋ถ„๋ฅ˜ : ๋‹ค์ด๋‚˜๋ฏน ํ”„๋กœ๊ทธ๋ž˜๋ฐ https://infinitt.tistory.com/246

 

์•Œ๊ณ ๋ฆฌ์ฆ˜ - ๋‹ค์ด๋‚˜๋ฏน ํ”„๋กœ๊ทธ๋ž˜๋ฐ (Dynamic Programming)

๋‹ค์ด๋‚˜๋ฏน ํ”„๋กœ๊ทธ๋ž˜๋ฐ (Dynamic Programming) : DP ๊ฐœ๋… : ๋ฌธ์ œ๋ฅผ ๋” ์ž‘์€ ๋‹จ์œ„๋กœ ์ชผ๊ฐœ์–ด ํ•ด๊ฒฐํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜. (๋ถ„ํ•  ์ •๋ณต ์•Œ๊ณ ๋ฆฌ์ฆ˜๊ณผ ๋น„์Šทํ•˜๋‹ค. ์ฐจ์ด์ ์€ ๋ฐ”๋กœ ์•„๋žซ์ค„.) ํ•ต์‹ฌ์€, ๊ทธ ์ž‘์€ ๋‹จ์œ„์˜ ๋ฌธ์ œ๋“ค์ด ๋ฐ˜๋ณตํ•ด์„œ..

infinitt.tistory.com

 

 

๊ณ„๋‹จ 3์นธ๊นŒ์ง€๋Š” ๋ช…ํ™•ํ•˜๋‹ค.

๊ณ„๋‹จ i์นธ๊นŒ์ง€ ์˜ค๋ฅผ๋•Œ์˜ ์ตœ๋Œ“๊ฐ’์„ dp[i] ๋ผ๊ณ  ๋†“๊ณ 

๋ฌธ์ œ์˜ ์ž…๋ ฅ(ํ•ด๋‹น ๊ณ„๋‹จ์˜ ์ˆซ์ž)๋ฅผ arr[k] ๋ผ๊ณ  ๋†“์œผ๋ฉด

dp [1] = arr[1]

dp [2] = arr[1] + arr[2]

dp [3] = max(arr[1] + arr[3] ,arr[2] + arr[3])

 

4์นธ์งธ ๋ถ€ํ„ฐ๋Š” ์ƒ๊ฐ์„ ์กฐ๊ธˆ ๋” ํ•ด์•ผ๋œ๋‹ค. (3์นธ ์—ฐ์†๋˜๋Š” ๊ณ„๋‹จ์„ ๋ฐŸ์„์ˆ˜ ์—†๋‹ค๋Š” ์กฐ๊ฑด๋•Œ๋ฌธ์—)

1. dp[i] = dp[i-2] + arr[i]        -> i์นธ์„ ๋ฐŸ๊ธฐ ์ „์˜ ์นธ์ด i-2์ด๋ฏ€๋กœ 3์นธ ์—ฐ์†๋ฐŸ์„์ผ์€ ์—†๋‹ค.

2. dp[i] = dp[i-1] + arr[i]        -> i์นธ ์ด์ „์— i-1 ์นธ์„ ๋ฐŸ์•˜์œผ๋ฏ€๋กœ, 3์นธ ์—ฐ์†์ผ ๊ฐ€๋Šฅ์„ฑ์ด ์กด์žฌํ•œ๋‹ค.

๋”ฐ๋ผ์„œ 2๋ฒˆ ์ ํ™”์‹์„ ๋ฐ”๊ฟ”์ค˜์•ผ ํ•œ๋‹ค. ํ•œ์นธ ์ „์˜ dp๊ฐ€ ์•„๋‹Œ, 3์นธ ์ „์˜ dp๋กœ ์ด๋™์‹œํ‚จ๋’ค์— ๋งˆ์ง€๋ง‰์นธ์€ ์…€ํ”„๋กœ ๋”ํ•ด์ฃผ๋ฉด 3์นธ ์—ฐ์†์ผ ๊ฐ€๋Šฅ์„ฑ์„ ์—†์•จ์ˆ˜ ์žˆ๋‹ค. 

์˜ฌ๋ฐ”๋ฅธ 2๋ฒˆ ์ ํ™”์‹ : dp[i] = dp[i-3] + arr[i-1] + arr[i]

 

 

 

๊ฒฐ๊ตญ ์ตœ์ข… ์ ํ™”์‹์€ 1๊ณผ 2์ค‘ ํฐ๊ฐ’์ด ๋˜๋ฏ€๋กœ dp[i] = max ( dp[i-2] + arr[i]   ,  dp[i-3] + arr[i-1] + arr[i] ) ๊ฐ€ ๋œ๋‹ค.

 

*์ •๋‹ต ์ฝ”๋“œ(Python)
import sys
input = sys.stdin.readline

N = int(input())
dp = [0 for _ in range(N+3)]
arr = [0 for _ in range(N+3)]
for k in range(1,N+1):
    arr[k] = int(input())


dp [1] = arr[1]
dp [2] = arr[1] + arr[2]
dp [3] = max(arr[1] + arr[3] ,arr[2] + arr[3])


for i in range(4, N+1):
    dp[i] = max( dp[i-3] + arr[i-1] + arr[i] ,  dp[i-2] + arr[i] ) 
print(dp[N])

 

Contents

ํฌ์ŠคํŒ… ์ฃผ์†Œ๋ฅผ ๋ณต์‚ฌํ–ˆ์Šต๋‹ˆ๋‹ค

์ด ๊ธ€์ด ๋„์›€์ด ๋˜์—ˆ๋‹ค๋ฉด ๊ณต๊ฐ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค.