알고리즘

백준 25325번 문제 풀이

kimhyeji 2025. 4. 21. 00:52

풀이 코드

_ = readLine()

// 1. 학생 이름을 Key로 딕셔너리 초기화
let students = readLine()!.split(separator: " ").map{String($0)}
var results: [String: Int] = [:]
for student in students {
    results.updateValue(0, forKey: student)
}

// 2. 학생 이름 Key에 따라 value 카운트업
while let input = readLine() {
    if input.contains(" ") {
        let picks = input.split(separator: " ").map{String($0)}
        picks.forEach { pick in
            results[pick]! += 1
        }
    } else {
        results[input]! += 1
    }
}

// 3. 정렬 : value 오름차순, value가 같다면 key(이름) 오름차순
let sorted = results.sorted(by: {
    if $0.value == $1.value {
        return $0.key < $1.key
    } else {
        return $0.value > $1.value
    }
})

for student in sorted {
    print("\(student.key) \(student.value)")
}
반응형