문제 소개
https://www.acmicpc.net/problem/1339
예를 들면 GCF + ACDEB 일 때 A부터 G까지 숫자를 부여한뒤 GCF + ACDEB 의 최댓값을 구하면 되는 문제이다.
문제 풀이
GCF + ACDEB 의 경우 각 번호에 1을 부여한다고 생각해 보면 아래와 같이 값이 나오게 되고, 높은 값부터 9를 부여해 주면 된다.
dictionary 로 데이터를 쌓아주고, 이것을 nums에 넣어준 뒤 높은 숫자부터 9부터 순서대로 곱해주면서 더하면 최댓값을 구할 수 있다.
import Foundation
let n = Int(readLine()!)!
var dict = [String: Int]()
for _ in 0..<n {
let input = Array(readLine()!).map { String($0) }
for i in input.indices {
if dict[input[input.count-i-1]] == nil {
dict[input[input.count-i-1]] = 0
}
dict[input[input.count-i-1]]! += Int(pow(10.0, Double(i)))
}
}
var nums = [Int]()
var answer = 0
for element in dict {
nums.append(element.value)
}
nums.sort(by: >)
for i in nums.indices {
answer += nums[i] * (9 - i)
}
print(answer)
결과는 아래와 같이 빠르게 시간이 나왔다. nums를 한번 정렬을 하긴 했지만 개수가 최대 9개여서 그런 듯싶다.
'→ Problems' 카테고리의 다른 글
[Algorithm] 백준 - 1182번 부분수열의 합 (Swift) (0) | 2024.05.29 |
---|---|
[Algorithm] 백준 - 14888번 연산자 끼워넣기 (Swift) (1) | 2024.05.29 |
[Algorithm] 백준 - 2529번 부등호 (Swift) (0) | 2024.05.28 |
[Algorithm] 백준 - 1167번 트리의 지름 (Swift) (0) | 2024.05.27 |
[Algorithm] 백준 - 1967번 트리의 지름 (Swift) (0) | 2024.05.27 |