K๋ฒˆ์งธ ํฐ ์ˆ˜(Swift)

2022. 9. 30. 14:55ใ†Algorithm

K๋ฒˆ์งธ ํฐ ์ˆ˜(Swift)

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

ํ˜„์ˆ˜๋Š” 1๋ถ€ํ„ฐ 100์‚ฌ์ด์˜ ์ž์—ฐ์ˆ˜๊ฐ€ ์ ํžŒ N์žฅ์˜ ์นด๋“œ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ๊ฐ™์€ ์ˆซ์ž์˜ ์นด๋“œ๊ฐ€ ์—ฌ๋Ÿฌ์žฅ ์žˆ์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ํ˜„์ˆ˜๋Š” ์ด ์ค‘ 3์žฅ์„ ๋ฝ‘์•„ ๊ฐ ์นด๋“œ์— ์ ํžŒ ์ˆ˜๋ฅผ ํ•ฉํ•œ ๊ฐ’์„ ๊ธฐ๋กํ•˜๋ ค ๊ณ  ํ•ฉ๋‹ˆ๋‹ค. 3์žฅ์„ ๋ฝ‘์„ ์ˆ˜ ์žˆ๋Š” ๋ชจ๋“  ๊ฒฝ์šฐ๋ฅผ ๊ธฐ๋กํ•ฉ๋‹ˆ๋‹ค. ๊ธฐ๋กํ•œ ๊ฐ’ ์ค‘ K๋ฒˆ์งธ๋กœ ํฐ ์ˆ˜๋ฅผ ์ถœ๋ ฅ ํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์„ธ์š”.

๋งŒ์•ฝ ํฐ ์ˆ˜๋ถ€ํ„ฐ ๋งŒ๋“ค์–ด์ง„ ์ˆ˜๊ฐ€ 25 25 23 23 22 20 19......์ด๊ณ  K๊ฐ’์ด 3์ด๋ผ๋ฉด K๋ฒˆ์งธ ํฐ ๊ฐ’ ์€ 22์ž…๋‹ˆ๋‹ค.

 

โ–ฃ ์ž…๋ ฅ์„ค๋ช…
์ฒซ ์ค„์— ์ž์—ฐ์ˆ˜ N(3<=N<=100)๊ณผ K(1<=K<=50) ์ž…๋ ฅ๋˜๊ณ , ๊ทธ ๋‹ค์Œ ์ค„์— N๊ฐœ์˜ ์นด๋“œ๊ฐ’์ด ์ž…๋ ฅ ๋œ๋‹ค.

 

โ–ฃ ์ถœ๋ ฅ์„ค๋ช…
์ฒซ ์ค„์— K๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค. K๋ฒˆ์งธ ์ˆ˜๋Š” ๋ฐ˜๋“œ์‹œ ์กด์žฌํ•ฉ๋‹ˆ๋‹ค.

 

โ–ฃ ์ž…๋ ฅ์˜ˆ์ œ 1
10 3
13 15 34 23 45 65 33 11 26 42

 

โ–ฃ ์ถœ๋ ฅ์˜ˆ์ œ

143

 

 

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

 

๋ฌธ์ œ๋ฅผ ๋ณด์ž๋งˆ์ž ์กฐํ•ฉ์„ ๋– ์˜ฌ๋ ธ๋‹ค.

ํ•˜์ง€๋งŒ "3์žฅ์„ ๋ฝ‘์•„"๋ผ๋Š” ์กฐ๊ฑด์„ ๋ณด์ž๋งˆ์ž ๊ฐ„๋‹จํ•œ for๋ฌธ์„ ๋Œ๋ฆฌ๋ฉด ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ์ผ์–ด๋‚ ๊นŒ? ๋ผ๋Š” ์ƒ๊ฐ๋ถ€ํ„ฐ ํ•˜๋Š” ๊ฒŒ ์ข‹์•˜์„ ๊ฒƒ ๊ฐ™๋‹ค. 

 

๋ฌธ์ œ์˜ ์˜ˆ์‹œ ์ž…๋ ฅ๊ฐ’์— ๋Œ€ํ•ด์„œ๋Š” ๊ฒฐ๊ณผ๊ฐ’์ด ๋งž์ง€๋งŒ ๊ฒฐ๊ณผ์ ์œผ๋กœ ๋‚ด๊ฐ€ ํ•œ ํ’€์ด๋Š” ํ‹€๋ ธ๋‹ค. 

๋งจ ๋งˆ์ง€๋ง‰์˜ "25 25 23 23 22 20 19......์ด๊ณ  K๊ฐ’์ด 3์ด๋ผ๋ฉด K๋ฒˆ์งธ ํฐ ๊ฐ’ ์€ 22์ž…๋‹ˆ๋‹ค."์€ ์ค‘๋ณต์„ ์ œ๊ฑฐํ•œ๋‹ค๋Š” ๋œป์ด๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. 

 

๊ทธ๋ž˜์„œ ๋ฌธ์ œ์˜ ์ €์ž์ฒ˜๋Ÿผ for๋ฌธ + Set์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์ด์šฉํ•ด์„œ ๋‹ค์‹œ ํ’€์–ด๋ณด์•˜๋‹ค

import Foundation

func combination(_ targetArr: [Int], _ k: Int) -> [[Int]] {
  var results: [[Int]] = []
  func cycle(_ index: Int, _ arr: [Int]) {
    if arr.count == k {
      results.append(arr)
      return
    }
    for i in index..<targetArr.count {
      cycle(i + 1, arr + [targetArr[i]])
    }
  }

  cycle(0, [])
  return results
}

let input = readLine()!
let results = input.components(separatedBy: " ").map{ Int($0)! }
let arrInput = readLine()!
let arrResult = arrInput.components(separatedBy: " ").map{ Int($0)! }


print(combination(arrResult, 3).map{ $0.reduce(0, +) }.sorted(by: >)[results[1]-1])

 

 

 ์ƒˆ๋กœ์šด ํ’€์ด

 

import Foundation

let input = readLine()!
let results = input.components(separatedBy: " ").map{ Int($0)! }
let arrInput = readLine()!
let arrResult = arrInput.components(separatedBy: " ").map{ Int($0)! }

var answers:Set<Int> = []
print(arrResult)
for i in 0..<arrResult.count {
  for j in i+1..<arrResult.count {
    for z in j+1..<arrResult.count {
      answers.insert(arrResult[i] + arrResult[j] + arrResult[z])
    }
  }
}
print(answers.map{$0}.sorted(by: >)[results[1]-1])

 

 ํ”ผ๋“œ๋ฐฑ

์ค‘๋ณต ์ œ๊ฑฐ์—๋Š” Set์ด ์ตœ๊ณ ์ธ๋“ฏ ํ•˜๋‹ค  โœจ