31 lines
877 B
Swift
31 lines
877 B
Swift
if let input = readLine(),
|
|
let seq = input.split(separator: " ").compactMap({Int($0)}) as? [Int]
|
|
{
|
|
let force: [[Int]] = [
|
|
[1,2,2,2,2],
|
|
[2,1,3,4,3],
|
|
[2,3,1,3,4],
|
|
[2,4,3,1,3],
|
|
[2,3,4,3,1]
|
|
]
|
|
|
|
var dp: [[[Int]]] = Array(repeating: Array(repeating: Array(repeating: 0, count: 5), count: 5), count: seq.count-1)
|
|
|
|
func solve(_ step: Int, _ l: Int, _ r: Int) -> Int {
|
|
if step == seq.count-1 { return 0 }
|
|
|
|
if dp[step][l][r] != 0 { return dp[step][l][r] }
|
|
|
|
let target = seq[step]
|
|
|
|
let moveLeftCost = solve(step + 1, target, r) + force[l][target]
|
|
let moveRightCost = solve(step + 1, l, target) + force[r][target]
|
|
|
|
dp[step][l][r] = min(moveLeftCost, moveRightCost)
|
|
|
|
return dp[step][l][r]
|
|
}
|
|
|
|
print(solve(0, 0, 0))
|
|
}
|