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

Algorithm/Baekjoon

[๋ฐฑ์ค€] (Swift) 9465๋ฒˆ - ์Šคํ‹ฐ์ปค (dp ํ’€์ด)

๊ฐ์ž ๐Ÿฅ” 2022. 3. 25. 00:29
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ ๋งํฌ

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

 

9465๋ฒˆ: ์Šคํ‹ฐ์ปค

์ฒซ์งธ ์ค„์— ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์˜ ๊ฐœ์ˆ˜ T๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์˜ ์ฒซ์งธ ์ค„์—๋Š” n (1 ≤ n ≤ 100,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ ๋‘ ์ค„์—๋Š” n๊ฐœ์˜ ์ •์ˆ˜๊ฐ€ ์ฃผ์–ด์ง€๋ฉฐ, ๊ฐ ์ •์ˆ˜๋Š” ๊ทธ ์œ„์น˜์— ํ•ด๋‹นํ•˜๋Š” ์Šคํ‹ฐ์ปค์˜

www.acmicpc.net

 

ํ’€์ด IDEA

์ด๋ ‡๊ฒŒ ๋ฐœ๊ฒฌํ•œ ์ ํ™”์‹์€ ์•„๋ž˜์™€ ๊ฐ™๋‹ค. ์—ฌ๊ธฐ์„œ dp ๋Š” ์œ„์— ๊ทธ๋ฆผ์œผ๋กœ ๋‚˜ํƒ€๋‚ธ ์ตœ๋Œ€๊ฐ’๋“ค์„ ์ €์žฅํ•˜๋Š” ๋ฐฐ์—ด์ด๊ณ , arr ๋Š” ์šฐ๋ฆฌ๊ฐ€ ์ž…๋ ฅ๋ฐ›์€ ์Šคํ‹ฐ์ปค๋“ค์˜ ๊ฐ€๊ฒฉ์ด ๋ช…์‹œ๋˜์–ด์žˆ๋Š” ๋ฐฐ์—ด์ด๋‹ค.

dp[0][i] = max(dp[1][i-1] + arr[0][i], dp[1][i-2] + arr[0][i])
dp[1][i] = max(dp[0][i-1] + arr[1][i], dp[0][i-2] + arr[1][i])

ํ•ด๋‹น ์ ํ™”์‹์„ ํ™œ์šฉํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ’€๋ฉด ๋œ๋‹ค.

 

์†Œ์Šค์ฝ”๋“œ  - ๋งž์•˜์Šต๋‹ˆ๋‹ค!

  • ๋‚˜๋Š” sticker ๋ผ๋Š” ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด dp ๋ฅผ ๊ตฌ์„ฑํ–ˆ๋‹ค.
  • ๊ทธ๋ฆฌ๊ณ  for ๋ฌธ์„ ์ด์šฉํ•ด์„œ ์Šคํ‹ฐ์ปค๋“ค์˜ ๋ฐฐ์—ด์„ ์ž…๋ ฅ๋ฐ›์•˜๋‹ค.
let count = Int(readLine()!)!

for _ in 1...count {
    let n = Int(readLine()!)!
    var arr: [Array<Int>] = []
    for _ in 0...1 {
        let input = readLine()!.split(separator: " ").map { Int(String($0))! }
        arr.append(input)
    }
    
    let result = sticker(n: n, arr: arr)
    
    if n == 1 {
        print(max(result[0][0], result[1][0]))
    } else if n == 2 {
        print(max(result[0][1], result[1][1]))
    } else {
        print(max(result[0][n-1], result[1][n-1]))
    }
}


func sticker(n: Int, arr: Array<Array<Int>>) -> Array<Array<Int>> {
    var dp = Array(repeating: Array(repeating: 0, count: n), count: 2)
    dp[0][0] = arr[0][0]
    dp[1][0] = arr[1][0]
    
    if n > 1 {
        dp[0][1] = arr[1][0] + arr[0][1]
        dp[1][1] = arr[0][0] + arr[1][1]
        
        for i in 2..<n {
           dp[0][i] = max(dp[1][i-1] + arr[0][i], dp[1][i-2] + arr[0][i])
           dp[1][i] = max(dp[0][i-1] + arr[1][i], dp[0][i-2] + arr[1][i])
           
        }
    }
    return dp
}
๋ฐ˜์‘ํ˜•