๋ฐฑ์ค€ - ์ค„ ์„ธ์šฐ๊ธฐ(Swift)

2022. 11. 8. 14:12ใ†Algorithm

๋ฐฑ์ค€ - ์ค„ ์„ธ์šฐ๊ธฐ(Swift)

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

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

 

10431๋ฒˆ: ์ค„์„ธ์šฐ๊ธฐ

์ดˆ๋“ฑํ•™๊ต ์„ ์ƒ๋‹˜ ๊ฐ•์‚ฐ์ด๋Š” ์•„์ด๋“ค์„ ๋ฐ๋ฆฌ๊ณ  ๋‹จ์ฒด๋กœ ์–ด๋–ค ์ผ์„ ํ•  ๋•Œ ๋ถˆํŽธํ•จ์ด ์—†๋„๋ก ์ƒˆ๋กœ ๋ฐ˜์— ๋ฐฐ์ •๋ฐ›์€ ์•„์ด๋“ค์—๊ฒŒ ํ‚ค ์ˆœ์„œ๋Œ€๋กœ ๋ฒˆํ˜ธ๋ฅผ ๋ถ€์—ฌํ•œ๋‹ค. ๋ฒˆํ˜ธ๋ฅผ ๋ถ€์—ฌํ•  ๋• ํ‚ค๊ฐ€ ๊ฐ€์žฅ ์ž‘์€ ์•„์ด๊ฐ€ 1

www.acmicpc.net

 

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

 

๋“ค์–ด๊ฐˆ ์ธ๋ฑ์Šค๋ฅผ ์ฐพ์•„์„œ ์‚ฝ์ž…ํ•ด์ฃผ๋ฉด ๋˜๋Š” ๋ฌธ์ œ๋‹ค.

์ฒ˜์Œ์—๋Š” ๋ฒ„๋ธ”์ •๋ ฌ๊ณผ ๊ฐ™์ด ๊ณ„์†ํ•ด์„œ ๊ฐ’์„ swapํ•˜๋Š” ํ˜•์‹์œผ๋กœ ๊ตฌํ˜„ํ–ˆ์—ˆ๋Š”๋ฐ ์ธ๋ฑ์Šค๋ฅผ ์ฐพ์•„์„œ ์‚ฝ์ž…ํ•˜๋Š”๊ฒŒ ๋”์šฑ ์ง๊ด€์ ์ด๋ผ๋Š” ์ƒ๊ฐ์ด ๋“ค์–ด์„œ ์•„๋ž˜์™€ ๊ฐ™์ด ๊ตฌํ˜„ํ–ˆ๋‹ค.

 

import Foundation

let tc = Int(readLine()!)!

for t in 0..<tc {
    let arr = readLine()!.components(separatedBy:" ").map{Int($0)!}
    let num = arr[0]
    var sortedArr = [arr[1]]
    var cnt = 0
    for i in 2..<arr.count {
        var insertIndex = sortedArr.count
        for j in stride(from: sortedArr.count-1, to: -1, by: -1) {
            if arr[i] > sortedArr[j] {
                break
            } else {
                insertIndex -= 1
                cnt += 1
            }
        }
        sortedArr.insert(arr[i], at: insertIndex)
    }
    print("\(t+1) \(cnt)")
}