๋ฐฑ์ค€ - 0 ๋งŒ๋“ค๊ธฐ(Swift)

2022. 11. 16. 15:29ใ†Algorithm

๋ฐฑ์ค€ - 0 ๋งŒ๋“ค๊ธฐ(Swift)

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

https://www.acmicpc.net/problem/7490

 

7490๋ฒˆ: 0 ๋งŒ๋“ค๊ธฐ

๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์— ๋Œ€ํ•ด ASCII ์ˆœ์„œ์— ๋”ฐ๋ผ ๊ฒฐ๊ณผ๊ฐ€ 0์ด ๋˜๋Š” ๋ชจ๋“  ์ˆ˜์‹์„ ์ถœ๋ ฅํ•œ๋‹ค. ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์˜ ๊ฒฐ๊ณผ๋Š” ํ•œ ์ค„์„ ๋„์›Œ ๊ตฌ๋ถ„ํ•œ๋‹ค.

www.acmicpc.net

 

 ๋‚˜์˜ ํ’€์ด

 

์ฒ˜์Œ ๋ฌธ์ œ๋ฅผ ๋ณด๊ณ  ํ…Œ์ŠคํŠธ์ผ€์ด์Šค์™€ N์˜ ๋ฒ”์œ„๊ฐ€ 10์ดํ•˜์ธ ๊ฒƒ์„ ํ™•์ธํ•˜๊ณ  +, -, ๊ณต๋ฐฑ 3๊ฐ€์ง€์˜ ๊ฒฝ์šฐ์ด๊ธฐ ๋•Œ๋ฌธ์— DFS๋กœ ์žฌ๊ท€๋ฅผ ๋Œ๋ ค์•ผ๊ฒ ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋‹ค. 

 

๊ตฌํ˜„์„ ํ•˜๋‹ค๊ฐ€ ํŒŒ์ด์ฌ์˜ evalํ•จ์ˆ˜๊ฐ€ ์Šค์œ„ํ”„ํŠธ์—๋Š” ๋”ฐ๋กœ ๋‚ด์žฅ๋˜์–ด์žˆ์ง€ ์•Š์•„์„œ ์ด๋ฅผ ์–ด๋–ป๊ฒŒ ๊ตฌํ˜„ํ• ์ง€ ๊ณ ๋ฏผํ•ด์•ผํ–ˆ๋‹ค.

๊ทธ๋ž˜์„œ ์ˆซ์ž๊ฐ€ ์•„๋‹Œ๊ฒƒ๋“ค๊ณผ ์ˆซ์ž์ธ ๊ฒƒ๋“ค๋กœ ๋ถ„๋ฆฌ๋ฅผ ์‹œํ‚จ ๋’ค ์Šคํƒ์— ์ €์žฅํ•ด์„œ ์—ฐ์‚ฐ์„ ํ•˜๋„๋ก ํ–ˆ๋‹ค.

 

๋งˆ์ง€๋ง‰์œผ๋กœ ์•„์Šคํ‚ค์ฝ”๋“œ ์ˆœ์œผ๋กœ ์ถœ๋ ฅ์ด๋˜์–ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— result๋ฅผ ์ „์—ญ๋ณ€์ˆ˜๋กœ ๋‹ค๋ค„์„œ ์ •๋ ฌํ•  ์ˆ˜ ์žˆ๊ฒŒ๋” ํ–ˆ๋‹ค.

 

import Foundation

let tc = Int(readLine()!)!
var result: [String] = []
for _ in 0..<tc {
    let N = Int(readLine()!)!
    let arr = Array(1...N)    
    DFS(1, "1", arr)
    result.sort(by: <) // ์•„์Šคํ‚ค์ฝ”๋“œ ์ˆœ์„œ๋ฅผ ์œ„ํ•ด ์ •๋ ฌ
    result.forEach { print($0) }
    print()
    result = []
}

func DFS(_ L: Int, _ str: String, _ arr: [Int]) {
    if L == arr.count { // ๋์— ๋„๋‹ฌํ–ˆ๋‹ค๋ฉด
        var stack: [Int] = [] // ๊ณ„์‚ฐํ•  ๊ณต๊ฐ„
        var str2 = str.replacingOccurrences(of:" ", with:"") //๊ณต๋ฐฑ์„ ์—†์• ์„œ ์ˆซ์ž๋ฅผ ๋ถ™์—ฌ์ค€๋‹ค.
        let nums = str2.split(whereSeparator: { !$0.isNumber })
        let seps = str2.split(whereSeparator: { $0.isNumber })
        var i = 0
        for x in nums {
            if stack.isEmpty {
                stack.append(Int(x)!)
            } else {
                let last = stack.removeLast()
                if seps[i] == "+" {
                    stack.append(last+Int(x)!)
                } else {
                    stack.append(last-Int(x)!)
                }
                i += 1
            }
        }
        if stack.last! == 0 { // ์—ฐ์‚ฐํ•œ ๊ฐ’์ด 0์ด๋ผ๋ฉด
            result.append(str)
        }
         
    } else { 
        DFS(L+1, str + "+\(arr[L])", arr)
        DFS(L+1, str + "-\(arr[L])", arr)
        DFS(L+1, str + " \(arr[L])", arr)    
    }
}

\