MUKER_DEV with iOS

[swift] λ°±μ€€ - 1874번: μŠ€νƒ μˆ˜μ—΄ λ³Έλ¬Έ

πŸ€– μ•Œκ³ λ¦¬μ¦˜/BAEKJOON

[swift] λ°±μ€€ - 1874번: μŠ€νƒ μˆ˜μ—΄

MUKER 2023. 2. 17. 08:49
 

1874번: μŠ€νƒ μˆ˜μ—΄

1λΆ€ν„° nκΉŒμ§€μ— μˆ˜μ— λŒ€ν•΄ μ°¨λ‘€λ‘œ [push, push, push, push, pop, pop, push, push, pop, push, push, pop, pop, pop, pop, pop] 연산을 μˆ˜ν–‰ν•˜λ©΄ μˆ˜μ—΄ [4, 3, 6, 8, 7, 5, 2, 1]을 얻을 수 μžˆλ‹€.

www.acmicpc.net

문제 ν‘ΈλŠ” 데 μžˆμ–΄ 도움이 λ˜λ„λ‘ λ‚˜μ˜ 풀이와 κ°œμ„ λœ 풀이λ₯Ό μ˜¬λ¦½λ‹ˆλ‹€.
λ˜ν•œ 풀이 ν›„ λ‹€λ₯Έ μ‚¬λžŒμ˜ 풀이λ₯Ό 보고 μ°Έκ³ ν• λ§Œν•œ 풀이도 μ˜¬λ¦½λ‹ˆλ‹€.

- λ¬Έμ œμ— 따라 λ‚˜μ˜ ν’€μ΄λ§Œ μžˆμ„ 수 μžˆμŠ΅λ‹ˆλ‹€.
- ν•΄λ‹Ή 풀이듀은 풀이 쀑 ν•˜λ‚˜μΌ 뿐 μ΅œμ„ μ˜ ν’€μ΄λŠ” 아닐 수 μžˆμŠ΅λ‹ˆλ‹€.

 


 

λ‚˜μ˜ 풀이

import Foundation

let input = Int(readLine()!)!
var arr = (0..<input).map { _ in Int(readLine()!)! }
var stack = [Int]()
var result = [String]()
var count = 0
for i in 1...(input+1) { 
    guard !stack.isEmpty else {
        stack.append(i)
        result.append("+")
        continue
    }
    
    while count < arr.count && arr[count] == stack.last {
        stack.removeLast()
        count += 1
        result.append("-")
    }
    
    stack.append(i)
    result.append("+")
    
}
if stack.count == 1 {
    result.removeLast()
    for i in result {
        print(i)
    }
} else { print("NO") }

 


 

μ°Έκ³ ν• λ§Œν•œ 풀이

let n = Int(readLine()!)!
var stack:[Int] = [0]
var count = 0
var str = ""
for _ in 1...n {
    let num = Int(readLine()!)!
    while count < num {
        count += 1
        stack.append(count)
        str += "+\n"
    }
    if stack.popLast() != num {
        str = "NO"
        break
    }
    str += "-\n"
}
print(str)

 

- μ €μ˜ 풀이와 μ•Œκ³ λ¦¬μ¦˜μ€ λΉ„μŠ·ν•˜μ§€λ§Œ

훨씬 μ§κ΄€μ μ΄λ„€μš”.