๋ฐฑ์ค - ์นํจ๋ฐฐ๋ฌ(Swift)
2022. 11. 18. 13:19ใAlgorithm
๋ฐฑ์ค - ์นํจ๋ฐฐ๋ฌ(Swift)
๋ฌธ์ ์ค๋ช
https://www.acmicpc.net/problem/15686
๋์ ํ์ด
์ ๋ ฅ์กฐ๊ฑด์ด ์์ ๊ฒ์ ๋ณด๊ณ ์์ ํ์์ ์๊ฐํ๊ณ ์ด ๋๋ฌธ์ ์กฐํฉ์ ์ด์ฉํด์ ๋ฌธ์ ๋ฅผ ํ์๋ค.
ํ์ง๋ง ๋ฌธ์ ๋ฅผ ํธ๋๋ฐ ์กฐ๊ธ ์ค๋๊ฑธ๋ ธ๋๋ฐ ๊ทธ ์ด์ ๊ฐ ์ง๋ค์ ๋ํด์ ๊ฐ์ฅ ๊ฐ๊น์ด ์นํจ์ง์ ๊ตฌํ๋ ๊ฒ์ด ์๋ ์นํจ์ง๋ค์ ๋ํด์ ๊ฐ์ฅ ๊ฐ๊น์ด ์ง์ ์ฐพ์๋ ๊ฒ์ด๋ค. ์ด ๋ฌธ์ ๋ ๋ชจ๋ ์ง์์ ๊ฐ์ฅ ๊ฐ๊น์ด ์นํจ์ง๊น์ง์ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ๋ ๊ฒ์ธ๋ฐ ๋ง์ด๋ค.
์ด ๋ถ๋ถ์ ํด๊ฒฐํ๋ ๋ฌธ์ ๊ฐ ๋ฐ๋ก ํ๋ ธ๋ค.
import Foundation
let input = readLine()!.components(separatedBy:" ").map{Int($0)!}
let N = input[0], M = input[1]
var map = [[Int]]()
var chickens = [(Int, Int)]()
var houses = [(Int, Int)]()
var result = Int.max
for _ in 0..<N {
let arr = readLine()!.components(separatedBy:" ").map{Int($0)!}
map.append(arr)
}
for i in 0..<N {
for j in 0..<N {
if map[i][j] == 2 {
chickens.append((i,j))
} else if map[i][j] == 1 {
houses.append((i,j))
}
}
}
let combinedChickens = combination(chickens, M)
for chicks in combinedChickens {
var sum = 0
for x in houses {
var minVal = Int.max
for y in chicks {
minVal = min(minVal, distance(x,y))
}
sum += minVal
}
result = min(result, sum)
}
print(result)
func combination<T>(_ targetArr: [T], _ n : Int) -> [[T]] {
var results = [[T]]()
if targetArr.count < n { return results }
func cycle(_ idx: Int, _ arr: [T]) {
if arr.count == n {
results.append(arr)
return
}
for i in idx..<targetArr.count {
cycle(i+1, arr + [targetArr[i]])
}
}
cycle(0, [])
return results
}
func distance(_ chicken: (Int, Int), _ house: (Int, Int)) -> Int {
return abs(chicken.0 - house.0) + abs(chicken.1 - house.1)
}
'Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋ฐฑ์ค - ํฑ๋๋ฐํด 2(Swift) (0) | 2022.11.21 |
---|---|
๋ฐฑ์ค - ์ธ๊ตฌ์ด๋(Swift) (0) | 2022.11.21 |
๋ฐฑ์ค - ํฑํํ (Swift) (0) | 2022.11.16 |
๋ฐฑ์ค - 0 ๋ง๋ค๊ธฐ(Swift) (0) | 2022.11.16 |
๋ฐฑ์ค - ๋น๋ฐํธ์(Swift) (0) | 2022.11.15 |