๋ฐฑ์ค€ - ๋“ฑ์ˆ˜๊ตฌํ•˜๊ธฐ(Swift)

2022. 11. 9. 17:16ใ†Algorithm

๋ฐฑ์ค€ - ๋“ฑ์ˆ˜๊ตฌํ•˜๊ธฐ(Swift)

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

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

 

1205๋ฒˆ: ๋“ฑ์ˆ˜ ๊ตฌํ•˜๊ธฐ

์ฒซ์งธ ์ค„์— N, ํƒœ์ˆ˜์˜ ์ƒˆ๋กœ์šด ์ ์ˆ˜, ๊ทธ๋ฆฌ๊ณ  P๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. P๋Š” 10๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๊ณ , 50๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ •์ˆ˜, N์€ 0๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๊ณ , P๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ •์ˆ˜์ด๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๋ชจ๋“  ์ ์ˆ˜๋Š” 2,000,000,000๋ณด

www.acmicpc.net

 

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

 

๊ตฌํ˜„๋ฌธ์ œ๋กœ ์–ด๋ ต์ง€ ์•Š๊ฒŒ ํ’€์—ˆ๋‹ค.

ํ•ต์‹ฌ์€ ์œ„์—์„œ๋ถ€ํ„ฐ ๋ช‡๋ฒˆ์งธ์ธ์ง€๋ฅผ ๊ตฌํ•˜๋Š” ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์— ์ž…๋ ฅ๋ฐ›์€ ์ ์ˆ˜๋ณด๋‹ค ํฐ ๊ฐ’์ด ๋ช‡๊ฐœ์ธ์ง€๋งŒ ์นด์šดํŠธํ•˜๋ฉด ๋œ๋‹ค.

 

๋‹ค๋ฅธ์‚ฌ๋žŒ์˜ ํ’€์ด๋ฅผ ๋ณด๋‹ˆ ๋‚˜๋Š” ๋ฐฐ์—ด์— ์‹ค์ œ๋กœ ๊ฐ’์„ ๋„ฃ์—ˆ๋Š”๋ฐ ๋”ฑํžˆ ๊ทธ๋Ÿดํ•„์š”๊ฐ€ ์—†์—ˆ๋‹ค. ๋ฐ”๋กœ arr์˜ ์›์†Œ๋“ค๊ณผ ์ƒˆ๋กœ ๋“ค์–ด์˜จ ๊ฐ’์„ ๋น„๊ตํ•จ์œผ๋กœ์จ Rank๋ฅผ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค.

 

import Foundation

let input = readLine()!.components(separatedBy:" ").map{Int($0)!}
let N = input[0], score = input[1], P = input[2] // ๊ฐœ์ˆ˜, ์ ์ˆ˜, ์ˆ˜์šฉ์น˜

if N == 0 { // ํ˜„์žฌ ๋‹ด๊ณ ์žˆ๋Š”๊ฒŒ ์—†๋‹ค๋ฉด 1๋“ฑ์„ ์ถœ๋ ฅ
    print("1")
    exit(0)
}

var arr = readLine()!.components(separatedBy:" ").map{Int($0)!}
if N == P && arr[N-1] >= score { // ์ˆ˜์šฉ์น˜๊ฐ€ ๊ฝ‰์ฐฌ ์ƒํƒœ์ด๋ฉด์„œ ๋์˜ ๊ฐ’์ด ์ž…๋ ฅ๊ฐ’๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๋‹ค๋ฉด ์‚ฝ์ž… ๋ถˆ๊ฐ€
    print("-1")    
} else {
    var insertIndex = arr.count
    for (i, x) in arr.enumerated() { 
        if score > x {
            insertIndex = i // ์ ์ˆ˜๋ฅผ ์‚ฝ์ž…ํ•  ์œ„์น˜๋ฅผ ๊ตฌํ•จ
            break
        }
    }
    arr.insert(score, at: insertIndex)
    var rank = 1
    for x in arr {
        if arr[insertIndex] < x { // ์‚ฝ์ž…๋œ ์œ„์น˜์˜ ๊ฐ’๋ณด๋‹ค ํฐ๊ฐ’์ด ์กด์žฌํ•˜๋ฉด rank๋ฅผ ์˜ฌ๋ ค์คŒ
            rank += 1
        }
    }
    print(rank)
}