๋ฐฑ์ค€ - ์„ธํƒ์†Œ ์‚ฌ์žฅ ๋™ํ˜(Swift)

2022. 10. 28. 10:36ใ†Algorithm

๋ฐฑ์ค€ - ์„ธํƒ์†Œ ์‚ฌ์žฅ ๋™ํ˜(Swift)

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

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

 

2720๋ฒˆ: ์„ธํƒ์†Œ ์‚ฌ์žฅ ๋™ํ˜

๊ฐ ํ…Œ์ŠคํŠธ์ผ€์ด์Šค์— ๋Œ€ํ•ด ํ•„์š”ํ•œ ์ฟผํ„ฐ์˜ ๊ฐœ์ˆ˜, ๋‹ค์ž„์˜ ๊ฐœ์ˆ˜, ๋‹ˆ์ผˆ์˜ ๊ฐœ์ˆ˜, ํŽ˜๋‹ˆ์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„ํ•˜์—ฌ ์ถœ๋ ฅํ•œ๋‹ค.

www.acmicpc.net

 

 ๋‚˜์˜ ํ’€์ด

 

๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๋Š”๋ฐ ์–ด๋ ค์›€์ด ์žˆ์ง€๋Š” ์•Š์•˜์ง€๋งŒ ๋”•์…”๋„ˆ๋ฆฌ ๋‚ด๋ถ€ ๊ฐ’์„ ์ดˆ๊ธฐ์— 0์œผ๋กœ ์ดˆ๊ธฐํ™”ํ•˜๊ฑฐ๋‚˜ joined๋Š” String๋ฐฐ์—ด์—๋งŒ ์ ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฒƒ๊ณผ joined์— ๊ณต๋ฐฑ๊ฐ’์„ ์ฃผ๊ธฐ์œ„ํ•ด์„œ๋Š” separator๋ณ€์ˆ˜๋ฅผ ์จ์•ผํ•˜๋Š” ๋“ฑ์˜ ๊ณ ๋ฏผ์ด ํ•„์š”ํ–ˆ๋‹ค.

 

๊ทธ๋ฆฌ๊ณ  ๋”•์…”๋„ˆ๋ฆฌ์—์„œ key๊ฐ’์„ ๊ธฐ์ค€์œผ๋กœ values๋งŒ ๋ฝ‘๊ณ  ์‹ถ์„๋•Œ๋Š” sortedํ•œ ๋’ค์— value๋งŒ ๋ฝ‘์œผ๋ฉด ๋œ๋‹ค.

์˜ˆ์‹œ๋กœ [3:4, 1:2]๋ผ๋Š” ๋”•์…”๋„ˆ๋ฆฌ๊ฐ€ ์žˆ๋‹ค๋ฉด

sortedํ–ˆ์„๋•Œ [(key:1, value:2), (key:3, value:4)]๊ฐ€ ๋‚˜์˜จ๋‹ค. ์ฆ‰ ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ๋ฐฐ์—ด๋กœ ๋งŒ๋“ค๋•Œ๋Š” key, value ํ•œ ์Œ์œผ๋กœ ํŠœํ”Œํ˜•ํƒœ๋กœ ๋‚˜์˜ค๋Š” ๊ฒƒ์ด๋‹ค.

 

import Foundation

func findMoney(_ num: Int) -> String {
    let arr = [25, 10, 5, 1]
    var dic: [Int: Int] = [25: 0, 10: 0, 5: 0, 1: 0]
    var num = num
    var idx = 0
    
    while num > 0 {
        if num >= arr[idx] {
            dic[arr[idx]] = num / arr[idx]
            num = num % arr[idx]
        }
        idx += 1
    }
    return dic.sorted(by: >).map{String($0.value)}.joined(separator: " ")
}


func main() {
    let n = Int(readLine()!)!
    for _ in 0..<n {
        let num = Int(readLine()!)!
        print(findMoney(num))
    }
}

main()