๋ฐฑ์ค€ - ํฌ๋กœ์Šค์ปจํŠธ๋ฆฌ(Swift)

2022. 11. 9. 14:25ใ†Algorithm

๋ฐฑ์ค€ - ํฌ๋กœ์Šค์ปจํŠธ๋ฆฌ(Swift)

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

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

 

9017๋ฒˆ: ํฌ๋กœ์Šค ์ปจํŠธ๋ฆฌ

์ž…๋ ฅ ๋ฐ์ดํ„ฐ๋Š” ํ‘œ์ค€์ž…๋ ฅ์„ ์‚ฌ์šฉํ•œ๋‹ค. ์ž…๋ ฅ์€ T ๊ฐœ์˜ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋กœ ์ฃผ์–ด์ง„๋‹ค. ์ž…๋ ฅ ํŒŒ์ผ์˜ ์ฒซ ๋ฒˆ์งธ ์ค„์— ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์˜ ์ˆ˜๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์ •์ˆ˜ T ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‘ ๋ฒˆ์งธ ์ค„๋ถ€ํ„ฐ๋Š” ๋‘ ์ค„์— ํ•˜๋‚˜์˜

www.acmicpc.net

 

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

 

๊ตฌํ˜„ ๋ฌธ์ œ๋Š” ์›๋ž˜ ์ด๋ ‡๊ฒŒ ํ‘ธ๋Š”๊ฑธ๊นŒ?

์•Œ๊ณ ๋ฆฌ์ฆ˜์€ ๊ฐ„๋‹จํ•˜์ง€๋งŒ ๋ฌด์—‡๋ณด๋‹ค ๊ผผ๊ผผํ•˜๊ฒŒ ๋ฌธ์ œ์˜ ์š”๊ตฌ์‚ฌํ•ญ์„ ๊ตฌํ˜„ํ•˜๋Š”๊ฒŒ ๊ด€๊ฑด์ด๋‹ค.

๋‚ด๊ฐ€ ๋†“์ณค๋˜ ๋ถ€๋ถ„์€ ๊ฐ€์žฅ ์ƒ์œ„์˜ ์„ ์ˆ˜ 4๋ช…์˜ ์ ์ˆ˜๋กœ ํŒ๋‹จํ•˜๋Š” ๊ฒƒ๊ณผ ์ด ์ ์ˆ˜๋Š” ๋†’์„์ˆ˜๋ก ์ข‹์€ ๊ฒƒ์ด ์•„๋‹Œ ๋‚ฎ์„์ˆ˜๋ก ์ข‹๋‹ค๋Š” ๊ฒƒ์ด๋‹ค.

 

์ฝ”๋“œ๋ฅผ ์งœ๋ฉด์„œ ๋„ˆ๋ฌด ๊ธธ์–ด์ง€๋Š” ๊ฒŒ ์•„๋‹Œ๊ฐ€ ์˜์‹ฌ์„ ํ–ˆ์ง€๋งŒ ๊ฒฐ๊ตญ ํ’€๊ณ ๋ณด๋‹ˆ ์˜์‹ฌํ•  ์—ฌ์ง€๊ฐ€ ์—†์—ˆ๋˜ ๊ฒƒ ๊ฐ™๋‹ค.

 

import Foundation

let tc = Int(readLine()!)!

for _ in 0..<tc {
    var dic = [Int: [Int]]() // ๊ฐ ํŒ€์ด ์–ป๋Š” ์ ์ˆ˜๋“ค
    var set1: Set<Int> = [] // ํŒ€์˜ ์ข…๋ฅ˜
    let n = Int(readLine()!)!
    var arr = readLine()!.components(separatedBy:" ").map{Int($0)!}
    set1 = Set(arr)
    for x in set1 {
        let cnt = arr.filter{$0 == x}.count
        if cnt < 6 { // ์„ ์ˆ˜๊ฐ€ 6๋ช… ์•„๋ž˜๋ฉด ์ œ์™ธ
            arr = arr.filter{$0 != x}
        }
    }
    var value = 1 // ์ ์ˆ˜
    for x in arr {
        if dic[x] == nil {
            dic[x] = [value]
        } else { 
            dic[x]!.append(value)
        }
        value += 1
    }
    var reduceArr = dic.map{ a in 
        return (a.key, (0...3).map{ a.value[$0] }.reduce(0, +)) //๊ฐ€์žฅ ์ƒ์œ„์˜ 4๋ช…์˜ ์ ์ˆ˜๋ฅผ ๋ˆ„์ 
    }
    var minVal = 1001
    for x in reduceArr {
        if x.1 < minVal { // ์ œ์ผ ๋‚ฎ์€ ์ ์ˆ˜๋ฅผ ๊ฐ€์ง„ ํŒ€์˜ ์ ์ˆ˜
            minVal = x.1
        }
    }
    var fillArr = reduceArr.filter{$0.1 == minVal}
    if fillArr.count > 1 { // ์ œ์ผ ๋‚ฎ์€ ์ ์ˆ˜๋ฅผ ๊ฐ€์ง„ ํŒ€์ด ์—ฌ๋Ÿฌ ํŒ€์ด๋ผ๋ฉด
        var min = 1001
        var result = 0
        for x in fillArr {
            if min > dic[x.0]![4] { //๋‹ค์„ฏ๋ฒˆ์งธ์˜ ์„ ์ˆ˜๋ฅผ ๋น„๊ตํ•œ๋‹ค.
                min = dic[x.0]![4]
                result = x.0
            }
        }
        print(result)    
    } else {
        print(fillArr[0].0) // ์ œ์ผ ๋‚ฎ์€ ์ ์ˆ˜๋ฅผ ๊ฐ€์ง„ ํŒ€์ด ํ•˜๋‚˜๋ผ๋ฉด ๊ทธ ํŒ€์„ ์ถœ๋ ฅ
    }
}