
๋ฐฑ์ค ๋ฌธ์ ๋ฅผ ํ๋ค ์๊ธด ์ผ์ด๋ค.
https://www.acmicpc.net/problem/1620
1620๋ฒ: ๋๋์ผ ํฌ์ผ๋ชฌ ๋ง์คํฐ ์ด๋ค์
์ฒซ์งธ ์ค์๋ ๋๊ฐ์ ์๋ก๋์ด ์๋ ํฌ์ผ๋ชฌ์ ๊ฐ์ N์ด๋ ๋ด๊ฐ ๋ง์ถฐ์ผ ํ๋ ๋ฌธ์ ์ ๊ฐ์ M์ด ์ฃผ์ด์ ธ. N๊ณผ M์ 1๋ณด๋ค ํฌ๊ฑฐ๋ ๊ฐ๊ณ , 100,000๋ณด๋ค ์๊ฑฐ๋ ๊ฐ์ ์์ฐ์์ธ๋ฐ, ์์ฐ์๊ฐ ๋ญ์ง๋ ์์ง? ๋ชจ๋ฅด๋ฉด
www.acmicpc.net
1. Array๋ง ์ฌ์ฉ (์๊ฐ ์ด๊ณผ)
๋งจ ์ฒ์์๋ Array๋ง์ ์ฌ์ฉํ๋ค. Index๋ฅผ ์ฌ์ฉํด์ ๋ฒํธ๋ฅผ ๊ตฌ๋ถํ ์๊ฐ์ด์๋ค.
func ๋๋์ผ_ํฌ์ผ๋ชฌ๋ง์คํฐ_์ด๋ค์() {
let input = readLine()!.split(separator: " ").compactMap { Int($0) }
var pokedex = [String]()
var answer = ""
for _ in 1...input[0] {
let pokemon = readLine()!
pokedex.append(pokemon)
}
for _ in 1...input[1] {
let question = readLine()!
if let number = Int(question) {
answer += "\(pokedex[number - 1])\n"
} else {
let pokemonIndex = pokedex.firstIndex(of: question)
answer += "\(pokemonIndex! + 1)\n"
}
}
print(answer)
}
๋๋์ผ_ํฌ์ผ๋ชฌ๋ง์คํฐ_์ด๋ค์()
๊ทธ๋ฐ๋ฐ ์ด๋ ๊ฒ ํ๋๋ ์๊ฐ ์ด๊ณผ๊ฐ ๋ฌ๋ค!
firstIndex๋ฅผ ํ์ธํ๋ฉด์ O(n)์ด๋ผ ์ค๋๊ฑธ๋ฆฌ๋ ๊ฒ ๊ฐ์๋ค.
2. Dictionary 2๊ฐ ์ฌ์ฉ (๋ง์์ต๋๋ค, 256ms)
Dictionary๋ Set ๋ฑ HashValue๋ก ๊ฐ์ ์ฐพ๋ ๊ฒฝ์ฐ๋ Array๋ณด๋ค ์กฐ๊ธ ๋ ๋น ๋ฅด๋ค. ๊ตณ์ด ์ ๋ถ ๋์๋ณผ ํ์๊ฐ ์๊ธฐ ๋๋ฌธ์ด๋ค.
func ๋๋์ผ_ํฌ์ผ๋ชฌ๋ง์คํฐ_์ด๋ค์() {
let input = readLine()!.split(separator: " ").compactMap { Int($0) }
var numberPokedex = [Int: String]()
var namePokedex = [String: Int]()
var answer = ""
for i in 1...input[0] {
let pokemon = readLine()!
numberPokedex[i] = pokemon
namePokedex[pokemon] = i
}
for _ in 1...input[1] {
let question = readLine()!
if let number = Int(question) {
answer += "\(String(describing: numberPokedex[number]!))\n"
} else {
answer += "\(String(describing: namePokedex[question]!))\n"
}
}
print(answer)
}
๋๋์ผ_ํฌ์ผ๋ชฌ๋ง์คํฐ_์ด๋ค์()
๊ทธ๋ฌ๋ value๊ฐ์ผ๋ก key ๊ฐ์ ์ฐพ๋ ๊ฒ์ hashValue๋ฅผ ์ด์ฉํ ๊ฒ์ด ์๋๊ธฐ์ ๋ฐ๋๋๋ ๊ฒ๊น์ง Dictionary๋ฅผ ๋ ๊ฐ ๋ง๋ค์ด ๊ตฌ๋ถํ์๋ค.
ํ์ง๋ง ๋ ๋์ ๋ฐฉ๋ฒ์ด ์์๊น ๊ณ ๋ฏผํ๋ค.
3. Dictionary์ Array์ ์ฌ์ฉ (๋ง์์ต๋๋ค, 204ms)
์ด๋ฆ์ key, ๋ฒํธ๋ฅผ value๋ก ํ๋ ๊ฒฝ์ฐ๋ ์ด์ฉ ์ ์์ง๋ง, ๋ฐ๋์ ๊ฒฝ์ฐ๋ array์ subscript๋ก ์ ๊ทผํ ์ ์๋ค.
func ๋๋์ผ_ํฌ์ผ๋ชฌ๋ง์คํฐ_์ด๋ค์() {
let input = readLine()!.split(separator: " ").compactMap { Int($0) }
var numberPokedex = [String]()
var namePokedex = [String: Int]()
var answer = ""
for i in 1...input[0] {
let pokemon = readLine()!
numberPokedex.append(pokemon)
namePokedex[pokemon] = i
}
for _ in 1...input[1] {
let question = readLine()!
if let number = Int(question) {
answer += "\(numberPokedex[number - 1])\n"
} else {
answer += "\(namePokedex[question]!)\n"
}
}
print(answer)
}
๋๋์ผ_ํฌ์ผ๋ชฌ๋ง์คํฐ_์ด๋ค์()
๊ทธ๋ฌ๋๋ ์๊ฐ์ด ํจ์ฌ ์ค์ด๋ค์๋ค. ์ฐพ์์ ์ฌ์ฉํ๋ ๊ฒ๋ณด๋ค๋ subscript๋ฅผ ํตํ ์ ๊ทผ์ด ํจ์ฌ ๋น ๋ฅธ ๊ฒ ๊ฐ๋ค.
++ func ์์ด ์คํํ๋ฉด 188ms๊น์ง ๋นจ๋ผ์ง๋ค!
'๐ฅ๏ธ Computer Science' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Network] TLS/SSL (1) | 2024.10.28 |
---|---|
[ํจ๋ฌ๋ค์] ํจ์ํ ํ๋ก๊ทธ๋๋ฐ (1) | 2024.10.23 |
[๋์์ธ ํจํด]Delegate Pattern (2) | 2024.01.27 |