Potato
์•ˆ๋…•ํ•˜์„ธ์š”, ๊ฐ์žก๋‹ˆ๋‹ค?๐Ÿฅ” ^___^ ๐Ÿ˜บ github ๋ฐ”๋กœ๊ฐ€๊ธฐ ๐Ÿ‘‰๐Ÿป

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!)
    }
}
๋ฐ˜์‘ํ˜•