๊ธ€ ์ž‘์„ฑ์ž: ๊ฐœ๋ฐœํ•˜๋Š” ํ›ˆ์ด

๋ฌธ์ œ

๋ฌธ์ œ ์„ค๋ช…

ํŠธ๋Ÿญ ์—ฌ๋Ÿฌ ๋Œ€๊ฐ€ ๊ฐ•์„ ๊ฐ€๋กœ์ง€๋ฅด๋Š” ์ผ์ฐจ์„  ๋‹ค๋ฆฌ๋ฅผ ์ •ํ•ด์ง„ ์ˆœ์œผ๋กœ ๊ฑด๋„ˆ๋ ค ํ•ฉ๋‹ˆ๋‹ค. ๋ชจ๋“  ํŠธ๋Ÿญ์ด ๋‹ค๋ฆฌ๋ฅผ ๊ฑด๋„ˆ๋ ค๋ฉด ์ตœ์†Œ ๋ช‡ ์ดˆ๊ฐ€ ๊ฑธ๋ฆฌ๋Š”์ง€ ์•Œ์•„๋‚ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ๋‹ค๋ฆฌ์—๋Š” ํŠธ๋Ÿญ์ด ์ตœ๋Œ€ bridge_length๋Œ€ ์˜ฌ๋ผ๊ฐˆ ์ˆ˜ ์žˆ์œผ๋ฉฐ, ๋‹ค๋ฆฌ๋Š” weight ์ดํ•˜๊นŒ์ง€์˜ ๋ฌด๊ฒŒ๋ฅผ ๊ฒฌ๋”œ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋‹จ, ๋‹ค๋ฆฌ์— ์™„์ „ํžˆ ์˜ค๋ฅด์ง€ ์•Š์€ ํŠธ๋Ÿญ์˜ ๋ฌด๊ฒŒ๋Š” ๋ฌด์‹œํ•ฉ๋‹ˆ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด, ํŠธ๋Ÿญ 2๋Œ€๊ฐ€ ์˜ฌ๋ผ๊ฐˆ ์ˆ˜ ์žˆ๊ณ  ๋ฌด๊ฒŒ๋ฅผ 10kg๊นŒ์ง€ ๊ฒฌ๋””๋Š” ๋‹ค๋ฆฌ๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. ๋ฌด๊ฒŒ๊ฐ€ [7, 4, 5, 6]kg์ธ ํŠธ๋Ÿญ์ด ์ˆœ์„œ๋Œ€๋กœ ์ตœ๋‹จ ์‹œ๊ฐ„ ์•ˆ์— ๋‹ค๋ฆฌ๋ฅผ ๊ฑด๋„ˆ๋ ค๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๊ฑด๋„ˆ์•ผ ํ•ฉ๋‹ˆ๋‹ค.

๊ฒฝ๊ณผ ์‹œ๊ฐ„๋‹ค๋ฆฌ๋ฅผ ์ง€๋‚œ ํŠธ๋Ÿญ๋‹ค๋ฆฌ๋ฅผ ๊ฑด๋„ˆ๋Š” ํŠธ๋Ÿญ๋Œ€๊ธฐ ํŠธ๋Ÿญ

0 [] [] [7,4,5,6]
1~2 [] [7] [4,5,6]
3 [7] [4] [5,6]
4 [7] [4,5] [6]
5 [7,4] [5] [6]
6~7 [7,4,5] [6] []
8 [7,4,5,6] [] []

๋”ฐ๋ผ์„œ, ๋ชจ๋“  ํŠธ๋Ÿญ์ด ๋‹ค๋ฆฌ๋ฅผ ์ง€๋‚˜๋ ค๋ฉด ์ตœ์†Œ 8์ดˆ๊ฐ€ ๊ฑธ๋ฆฝ๋‹ˆ๋‹ค.

solution ํ•จ์ˆ˜์˜ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ๋‹ค๋ฆฌ์— ์˜ฌ๋ผ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ํŠธ๋Ÿญ ์ˆ˜ bridge_length, ๋‹ค๋ฆฌ๊ฐ€ ๊ฒฌ๋”œ ์ˆ˜ ์žˆ๋Š” ๋ฌด๊ฒŒ weight, ํŠธ๋Ÿญ ๋ณ„ ๋ฌด๊ฒŒ truck_weights๊ฐ€ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. ์ด๋•Œ ๋ชจ๋“  ํŠธ๋Ÿญ์ด ๋‹ค๋ฆฌ๋ฅผ ๊ฑด๋„ˆ๋ ค๋ฉด ์ตœ์†Œ ๋ช‡ ์ดˆ๊ฐ€ ๊ฑธ๋ฆฌ๋Š”์ง€ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•˜์„ธ์š”.

์ œํ•œ ์กฐ๊ฑด

  • bridge_length๋Š” 1 ์ด์ƒ 10,000 ์ดํ•˜์ž…๋‹ˆ๋‹ค.
  • weight๋Š” 1 ์ด์ƒ 10,000 ์ดํ•˜์ž…๋‹ˆ๋‹ค.
  • truck_weights์˜ ๊ธธ์ด๋Š” 1 ์ด์ƒ 10,000 ์ดํ•˜์ž…๋‹ˆ๋‹ค.
  • ๋ชจ๋“  ํŠธ๋Ÿญ์˜ ๋ฌด๊ฒŒ๋Š” 1 ์ด์ƒ weight ์ดํ•˜์ž…๋‹ˆ๋‹ค.

ํ’€์ด

๋‹จ์ˆœํ•˜๊ฒŒ ์‹œ๋ฎฌ๋ ˆ์ด์…˜์„ ๋Œ๋ฆฌ๋“ฏ์ด ํ•ด๊ฒฐํ–ˆ์Šต๋‹ˆ๋‹ค. ๋จผ์ € ๋‹ค๋ฆฌ์˜ ๊ธธ์ด๋งŒํผ์˜ ๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด์„œ ๋ชจ๋‘ 0์œผ๋กœ ์ฑ„์›Œ๋„ฃ๊ณ , ๋ฐ˜๋ณต๋ฌธ์„ ๋Œ๋ฉฐ ํ•œ ๋ฃจํ”„๊ฐ€ ์ง€๋‚  ๋•Œ๋งˆ๋‹ค 1์ดˆ๊ฐ€ ์ง€๋‚˜๋Š” ๊ฒƒ์œผ๋กœ ์ƒ์ •ํ–ˆ์Šต๋‹ˆ๋‹ค. 1์ดˆ๊ฐ€ ์ง€๋‚  ๋•Œ๋Š” ํ˜„์žฌ ๋‹ค๋ฆฌ ์œ„์— ์žˆ๋Š” ํŠธ๋Ÿญ๋“ค์˜ ๋ฌด๊ฒŒํ•ฉ์„ ๋‹ค๋ฆฌ๊ฐ€ ๊ฒฌ๋”œ ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€ ๋ฌด๊ฒŒ์™€ ๋น„๊ตํ•˜์—ฌ ์ƒˆ๋กœ์šด ํŠธ๋Ÿญ์„ ์˜ฌ๋ฆด ์ˆ˜ ์žˆ๋‹ค๋ฉด ์˜ฌ๋ฆฌ๊ณ , ์•„๋‹ˆ๋ผ๋ฉด ๋ฐฐ์—ด์˜ ๋ชจ๋“  ์š”์†Œ๋“ค์„ ํ•œ ์นธ์”ฉ ๋’ค๋กœ ๋ฐ€์–ด ํŠธ๋Ÿญ๋“ค์˜ ์œ„์น˜๋ฅผ ์›€์ง€์ด๋„๋ก ํ–ˆ์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ

import Foundation

func solution(_ bridge_length:Int, _ weight:Int, _ truck_weights:[Int]) -> Int {
    var bridge = Array(repeating: 0, count: bridge_length)
    var trucks = truck_weights
    var weightSum = trucks.first!
    var time = 1
    
    bridge[0] = trucks.removeFirst()
    
    while weightSum != 0 || !trucks.isEmpty {
        time += 1
        bridge.insert(0, at: 0)
        weightSum -= bridge.removeLast()
        
        if let nextTruck = trucks.first {
            if weightSum + nextTruck <= weight {
                bridge[0] = trucks.removeFirst()
                weightSum += bridge[0]
            }
        }
    }
    
    return time
}