Potato
์•ˆ๋…•ํ•˜์„ธ์š”, ๊ฐ์žก๋‹ˆ๋‹ค?๐Ÿฅ” ^___^ ๐Ÿ˜บ github ๋ฐ”๋กœ๊ฐ€๊ธฐ ๐Ÿ‘‰๐Ÿป

Algorithm/Baekjoon

[๋ฐฑ์ค€] (Swift) 2579๋ฒˆ - ๊ณ„๋‹จ ์˜ค๋ฅด๊ธฐ (dp ๊ธฐ๋ณธ๋ฌธ์ œ, ์‹ค๋ฒ„3)

๊ฐ์ž ๐Ÿฅ” 2022. 7. 12. 17:48
๋ฐ˜์‘ํ˜•

 

๐ŸŸ  ๋ฌธ์ œ๋งํฌ

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

 

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

๊ณ„๋‹จ ์˜ค๋ฅด๊ธฐ ๊ฒŒ์ž„์€ ๊ณ„๋‹จ ์•„๋ž˜ ์‹œ์ž‘์ ๋ถ€ํ„ฐ ๊ณ„๋‹จ ๊ผญ๋Œ€๊ธฐ์— ์œ„์น˜ํ•œ ๋„์ฐฉ์ ๊นŒ์ง€ ๊ฐ€๋Š” ๊ฒŒ์ž„์ด๋‹ค. <๊ทธ๋ฆผ 1>๊ณผ ๊ฐ™์ด ๊ฐ๊ฐ์˜ ๊ณ„๋‹จ์—๋Š” ์ผ์ •ํ•œ ์ ์ˆ˜๊ฐ€ ์“ฐ์—ฌ ์žˆ๋Š”๋ฐ ๊ณ„๋‹จ์„ ๋ฐŸ์œผ๋ฉด ๊ทธ ๊ณ„๋‹จ์— ์“ฐ์—ฌ ์žˆ๋Š” ์ 

www.acmicpc.net

 

๐ŸŸ  ๋ฌธ์ œ ํ’€์ด ์•„์ด๋””์–ด

๊ฐ€์žฅ ๊ธฐ์ดˆ์ ์ธ dp ๋ฌธ์ œ์ค‘ ํ•˜๋‚˜์˜€๋‹ค. ํ•˜์ง€๋งŒ ๊ฐ€์žฅ ์ค‘์š”ํ•œ๊ฒƒ์€, ์ƒ๊ฐ์„ ๋ฐ˜๋Œ€๋กœํ•ด์•ผํ•œ๋‹ค๋Š” ๊ฒƒ์ด์—ˆ๋‹ค.

"์ฒ˜์Œ๋ถ€ํ„ฐ ๊ณ„๋‹จ์„ ์–ด๋–ป๊ฒŒ ์˜ฌ๋ผ๊ฐ€์ง€?" ์ƒ๊ฐ๋ณด๋‹ค๋Š”, "์ตœ์ข… ๋„์ฐฉ์ง€๊ธฐ์ค€์œผ๋กœ ๋ดค์„๋•Œ, ์–ด๋””์„œ ์˜ฌ๋ผ์™“์ฐŒ?"๋ฅผ ๊ณ ๋ คํ•ด๋ด์•ผํ•œ๋‹ค๋Š” ๊ฒƒ์ด๋‹ค.
์—ฐ์†์œผ๋กœ 3์นธ์˜ ๊ณ„๋‹จ์„ ๋ฐŸ์„ ์ˆ˜๊ฐ€ ์—†๊ธฐ ๋•Œ๋ฌธ์—, ๋„์ฐฉ์ง€ ๊ธฐ์ค€์œผ๋กœ ์˜ฌ๋ผ์˜ฌ ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์€ ์•„๋ž˜ ๊ทธ๋ฆผ์ฒ˜๋Ÿผ ๋”ฑ ๋‘๊ฐ€์ง€ ๋ฐฉ๋ฒ•์ด๋‹ค.

์ด๋ ‡๊ฒŒ dp ์ ํ™”์‹์„ ์œ ๋„ํ•ด๋ƒˆ๋‹ค.

dp์ ํ™”์‹์— ๋‚ด๊ฐ€ ํ•œ ์‹ค์ˆ˜๋ฅผ ์ ์–ด๋‘์—ˆ๋‹ค. ์ ์–ด๋‘” ๊ฒƒ ์ฒ˜๋Ÿผ, ๊ทธ๋ฆผ์—์„œ โ‘ ๋ฒˆ ๋ฃจํŠธ์ธ ๊ฒฝ์šฐ์—๋Š”, dp[n-3] + dp[n-1] ๋กœ ํ•ด๋ฒ„๋ฆฌ๋ฉด, ๋ˆ„์ ๋œ ํ•ฉ์„ ๋‘๋ฒˆ์ด๋‚˜ ๋”ํ•ด์ฃผ๋Š” ๊ฒƒ๊ณผ ๊ฐ™์•„์ง„๋‹ค. ๊ทธ๋ž˜์„œ dp[n-3]์—๋‹ค๊ฐ€, ๋‚˜๋จธ์ง€ ๋‘๋ฒˆ์€ arr (๊ณ„๋‹จ ๊ฐ๊ฐ์˜ ๊ฐ’)์„ ๋”ํ•ด์ค€ ๊ฒƒ์„ ํ•ฉ์ณ์ค˜์•ผํ•œ๋‹ค!!

๋‚˜๋Š” ์—ฌ๊ธฐ์„œ dp[n-3] + dp[n-1] + arr[n] ์ด๋ผ๊ณ  ์ž‘์„ฑํ•ด์„œ ๋‹ต์ด ๋‚˜์˜ค์ง€ ์•Š์•„ ๊ฝค ์˜ค๋žซ๋™์•ˆ ๊ณ ๋ฏผํ–ˆ๋‹ค ๐Ÿ˜…

 

๐ŸŸ  ์ •๋‹ต ์ฝ”๋“œ

https://github.com/deslog/Algorithm/blob/main/Algorithm/Boj/2579_%EA%B3%84%EB%8B%A8%EC%98%A4%EB%A5%B4%EA%B8%B0/main.swift

 

GitHub - deslog/Algorithm

Contribute to deslog/Algorithm development by creating an account on GitHub.

github.com

let n = Int(String(readLine()!))!
var arr = [0]
for _ in 0..<n {
    arr.append(Int(String(readLine()!))!)
}

var dp = Array(repeating: 0, count: n+1)

// main
dp[0] = 0
for i in 1..<n+1 {
    if i == 1 {
        dp[1] = arr[1]
    } else if i == 2 {
        dp[2] = arr[1] + arr[2]
    } else if i == 3 {
        dp[3] = max(arr[3]+arr[1], arr[3]+arr[2])
    } else {
        dp[i] = max(arr[i] + arr[i-1] + dp[i-3], arr[i] + dp[i-2])
    }
}

print(dp[n])

 

๋ฐ˜์‘ํ˜•