๊ธ€ ์ž‘์„ฑ์ž: ์ด์ง€์›๐ŸŒฉ๏ธ

54:45

ํ‘ธ๋Š” ๋ฐ ์ •๋ง ์˜ค๋ž˜๊ฑธ๋ ธ๋‹ค. ์‚ฌ์‹ค ์ด ๋ฌธ์ œ๋Š” ์˜ˆ์ „์—๋„ ๋ช‡ ๋ฒˆ ์‹œ๋„ํ–ˆ๋‹ค๊ฐ€ ์‹คํŒจํ–ˆ๋Š”๋ฐ ์ด๋ฒˆ์—๋Š” ์„ฑ๊ณต!

  1. ์ผ๋‹จ, ์ฒ˜์Œ์—๋Š” ๋Œ€๊ธฐ ํŠธ๋Ÿญ ๋ชฉ๋ก์ด ๋น„์–ด์žˆ๊ณ , ํ(๋‹ค๋ฆฌ)๊ฐ€ ๋นŒ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•˜๊ฒŒ ํ–ˆ๋Š”๋ฐ ์ด์œ ๋Š” ๋ชฐ๋ผ๋„ ๋™์ž‘ํ•˜์ง€ ์•Š์•„์„œ ๋„์ฐฉํ•œ ํŠธ๋Ÿญ์˜ ์ˆ˜๊ฐ€ ์ž…๋ ฅ์œผ๋กœ ๋“ค์–ด์˜จ ๋Œ€๊ธฐ ํŠธ๋Ÿญ ์ˆ˜์™€ ๊ฐ™์„ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•˜๊ธฐ๋กœ ํ–ˆ๋‹ค.
  2. ๋‹ค๋ฆฌ๋ฅผ ๊ฑด๋„ˆ๊ณ  ์žˆ๋Š” ํŠธ๋Ÿญ์ด ์žˆ๋Š”์ง€ ํ™•์ธํ•œ๋‹ค. ์–ด์ฐจํ”ผ 1์ดˆ์— ํ•œ ๋Œ€์”ฉ๋ฐ–์— ๋ชป ์›€์ง์ด๋‹ˆ ๊ฐ€์žฅ ์ฒซ ํŠธ๋Ÿญ๋งŒ ํ™•์ธํ•˜๋ฉด ๋œ๋‹ค.
  3. ๋‹ค๋ฆฌ์— ์žˆ๋Š” ํŠธ๋Ÿญ์˜ ๋ฌด๊ฒŒ์™€ ๋Œ€๊ธฐ ํŠธ๋Ÿญ์˜ ๋งจ ์•ž์— ์žˆ๋Š” ํŠธ๋Ÿญ์˜ ๋ฌด๊ฒŒ๋ฅผ ํ•ฉํ–ˆ์„ ๋•Œ, ์ดˆ๊ณผํ•˜์ง€ ์•Š์œผ๋ฉด queue์— ๋„ฃ์–ด์ค€๋‹ค. ์ด ๋•Œ, ํ˜„์žฌ ์‹œ๊ฐ„์„ ๊ฐ™์ด ๋„ฃ์–ด์„œ 2์—์„œ ์‹œ๊ฐ„์„ ํ™•์ธํ•  ๋•Œ ์“ด๋‹ค.

๋ฌธ์ œ

https://programmers.co.kr/learn/courses/30/lessons/42583
https://www.acmicpc.net/problem/13335


๋‚ด๊ฐ€ ์ž‘์„ฑํ•œ ์ฝ”๋“œ

Swift

import Foundation  

func solution(_ bridge_length:Int, _ weight:Int, _ truck_weights:[Int]) -> Int {
    var waits = truck_weights // ๋Œ€๊ธฐ ํŠธ๋Ÿญ
    var queue = [[Int]]() // ๋‹ค๋ฆฌ๋ฅผ ๊ฑด๋„ˆ๋Š” ํŠธ๋Ÿญ 
    var finished = [[Int]]() // ๋‹ค๋ฆฌ๋ฅผ ์ง€๋‚œ ํŠธ๋Ÿญ
    var time = 0 // ๊ฒฝ๊ณผ ์‹œ๊ฐ„
    while finished.count != truck_weights.count { // ๋„์ฐฉ ํŠธ๋Ÿญ ๋ชฉ๋ก ์ˆ˜๊ฐ€ ์ž…๋ ฅ์œผ๋กœ ๋“ค์–ด์˜จ ๋Œ€๊ธฐ ํŠธ๋Ÿญ ์ˆ˜์™€ ๊ฐ™์„ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณต
        // finished <--- queue
        if !queue.isEmpty && time - queue[0][1] == bridge_length {
            finished.append(queue.removeFirst())
        }

        // queue <--- waits
        if let first = waits.first {
            if queue.map({ $0[0] }).reduce(0, +) + first <= weight {
                queue.append([waits.removeFirst(), time])
            }
        }

        time += 1
    }     
    return time 
}
๋ฐ˜์‘ํ˜•