λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
πŸ“– Problem Solution

[Swift] Baekjoon λ‚˜μ΄μˆœ μ •λ ¬ 10814번

by Fomagran πŸ’» 2022. 1. 30.
728x90
λ°˜μ‘ν˜•

 

Problem

 

 

10814번: λ‚˜μ΄μˆœ μ •λ ¬

온라인 저지에 κ°€μž…ν•œ μ‚¬λžŒλ“€μ˜ λ‚˜μ΄μ™€ 이름이 κ°€μž…ν•œ μˆœμ„œλŒ€λ‘œ 주어진닀. μ΄λ•Œ, νšŒμ›λ“€μ„ λ‚˜μ΄κ°€ μ¦κ°€ν•˜λŠ” 순으둜, λ‚˜μ΄κ°€ κ°™μœΌλ©΄ λ¨Όμ € κ°€μž…ν•œ μ‚¬λžŒμ΄ μ•žμ— μ˜€λŠ” μˆœμ„œλ‘œ μ •λ ¬ν•˜λŠ” ν”„λ‘œκ·Έλž¨μ„

www.acmicpc.net


Solution

 

1. λ”•μ…”λ„ˆλ¦¬λ₯Ό ν™œμš©ν•΄ μœ μ € 정보λ₯Ό λ„£λŠ”λ‹€.

 

keyκ°’μœΌλ‘œ λ‚˜μ΄λ₯Ό,valueκ°’μœΌλ‘œ 이름을 λ„£μŠ΅λ‹ˆλ‹€.

 

λ§Œμ•½ λ”•μ…”λ„ˆλ¦¬μ— key값이 λΉ„μ–΄μžˆμ§€ μ•Šλ‹€λ©΄ value에 μΆ”κ°€λ‘œ append ν•΄μ€λ‹ˆλ‹€.

 

var userDic:[Int:[String]] = [:]
let numberOfUser = Int(readLine()!)!
for _ in 0..<numberOfUser {
    let input = String(readLine()!)
    let split = input.split(separator: " ")
    let age = Int(split[0])!
    let name = "\(split[1])"
    addUser(age, name)
}

func addUser(_ age:Int,_ name:String) {
    if userDic[age] == nil {
        userDic[age] = [name]
    }else {
        userDic[age]!.append(name)
    }
}

 

2. λ”•μ…”λ„ˆλ¦¬λ₯Ό keyκ°’μœΌλ‘œ μ •λ ¬ν•΄ μœ μ € 정보λ₯Ό 좜λ ₯ν•œλ‹€.

 

let sort = userDic.sorted{$0.key < $1.key}
for user in sort {
    for name in user.value {
        print("\(user.key) \(name)")
    }
}

Source Code

 

728x90
λ°˜μ‘ν˜•

λŒ“κΈ€