2026-02-17 19:56:47 +09:00

34 lines
955 B
Swift

func solve() {
guard let N = Int(readLine() ?? "") else { return }
var size: [(Int, Int)] = []
for _ in 0..<N {
guard let input = readLine(),
let rc = input.split(separator: " ").compactMap({Int($0)}) as? [Int],
let r = rc.first, let c = rc.last
else { return }
size.append((r,c))
}
var dp = Array(repeating: Array(repeating: 0, count: N), count: N)
for len in 2...N {
for start in 0...(N - len) {
let end = start + len - 1
dp[start][end] = Int.max
for k in start..<end {
let op_left = dp[start][k]
let op_right = dp[k+1][end]
let op_merge = size[start].0 * size[k].1 * size[end].1
dp[start][end] = min(dp[start][end], op_left + op_right + op_merge)
}
}
}
print(dp[0][N-1])
}
solve()