Algorithm/Baekjoon
[๋ฐฑ์ค] (Swift) 10866๋ฒ - ๋ฑ(deque)
๊ฐ์ ๐ฅ
2022. 2. 6. 13:26
๋ฐ์ํ
๋ฌธ์ ๋งํฌ
https://www.acmicpc.net/problem/10866
10866๋ฒ: ๋ฑ
์ฒซ์งธ ์ค์ ์ฃผ์ด์ง๋ ๋ช ๋ น์ ์ N (1 ≤ N ≤ 10,000)์ด ์ฃผ์ด์ง๋ค. ๋์งธ ์ค๋ถํฐ N๊ฐ์ ์ค์๋ ๋ช ๋ น์ด ํ๋์ฉ ์ฃผ์ด์ง๋ค. ์ฃผ์ด์ง๋ ์ ์๋ 1๋ณด๋ค ํฌ๊ฑฐ๋ ๊ฐ๊ณ , 100,000๋ณด๋ค ์๊ฑฐ๋ ๊ฐ๋ค. ๋ฌธ์ ์ ๋์์์ง
www.acmicpc.net
๋ด๊ฐ ํผ ํ์ด
- ์ฝ๋ ๊ธธ์ด ์ ์์์ B๋ฅผ ๋ฐ์๋ค. ์ด๋ฅผ ์ค์ผ ์ ์๋ ๋ฐฉ๋ฒ, ๋ ํจ์จ์ ์ธ ์ฝ๋ฉ ๋ฐฉ๋ฒ์ด ๋ญ๊ฐ ์์๊น?
import Foundation
let n = Int(readLine()!)!
var answer: [String] = []
for _ in 0..<n {
var order = readLine()!.split(separator: " ").map { String($0) }
switch order[0] {
case "push_front":
answer.insert(order[1], at: 0)
case "push_back":
answer.append(order[1])
case "pop_front":
if answer.isEmpty {
print(-1)
}else{
print(answer.removeFirst())
}
case "pop_back":
if answer.isEmpty {
print(-1)
} else {
print(answer.removeLast())
}
case "size":
print(answer.count)
case "empty" :
if answer.isEmpty {
print(1)
}else {
print(0)
}
case "front" :
if answer.isEmpty {
print(-1)
} else {
print(answer[0])
}
default:
if answer.isEmpty {
print(-1)
} else{
print(answer.last!)
}
}
}
๋ค๋ฅธ ์ฌ๋ ํ์ด
- ๋ฐฑ์ค์ slow92๋์ ๊ณต๊ฐ๋ ์ฝ๋๋ฅผ ์ฐธ๊ณ ํ์๋ค
- if๋ฌธ์ ์ฌ์ฉํ์ง ์๊ณ ์กฐ๊ฑด ? true:false ๊ตฌ๋ฌธ์ ์ฌ์ฉํ๋ฉด ์กฐ๊ธ ๋ ์งง์ ์ฝ๋ ๊ตฌํ์ด ๊ฐ๋ฅํ๋ค.
- ๋ฌธ์ ํผ์ฌ๋๋ค์ ์ฝ๋ ๊ธธ์ด๋ฅผ ๋ณด๋, ์ ๋ถ B๋ฅผ ๋ฐ์๊ธฐ ๋๋ฌธ์ ์ด๋ ํ๊ท ์ ์ธ ์์น์ธ๊ฒ ๊ฐ๋ค.
- ๊ทธ๋ฆฌ๊ณ ๋๋ถ๋ถ์์ฌ๋๋ค์ด switch case ํน์ func ์ผ๋ก ๋ฌธ์ ๋ฅผ ํ์๋ค.
var D:[Int] = []
for _ in 0..<Int(readLine()!)! {
let C = readLine()!.split{$0==" "}.map{String($0)}
let command = C.first!
var num = 0
if C.count > 1 {
num = Int(C.last!)!
}
switch command {
case "push_front": D.insert(num, at: 0)
case "push_back": D.append(num)
case "pop_front": print(D.isEmpty ? -1:D.removeFirst())
case "pop_back": print(D.isEmpty ? -1:D.removeLast())
case "size": print(D.count)
case "empty": print(D.isEmpty ? 1:0)
case "front": print(D.isEmpty ? -1:D.first!)
default: print(D.isEmpty ? -1:D.last!)
}
}
๋ฐ์ํ