問題
Matrix i has size dimensions[i] × dimensions[i+1]. Multiplying a p×q matrix by a q×r matrix costs p·q·r scalar multiplications. Choose where to put parentheses so multiplying the whole chain costs the least.
Implement min_multiplications(dimensions).
Input
dimensions: n + 1 sizes describing n matrices.
Output
Return the minimum total cost.
制約
2 ≤ length of dimensions ≤ 200; 1 ≤ each size ≤ 500
例
入力:
dimensions = [10, 30, 5, 60]
期待される出力:
expected = 4500
入力:
std::vector<long long> dimensions = {10, 30, 5, 60};
期待される出力:
long long expected = 4500;
入力:
long[] dimensions = new long[] {10, 30, 5, 60};
期待される出力:
long expected = 4500;
解説
(A×B)×C costs 10·30·5 + 10·5·60 = 4500, cheaper than A×(B×C) = 27000.
入力:
dimensions = [5, 10]
期待される出力:
expected = 0
入力:
std::vector<long long> dimensions = {5, 10};
期待される出力:
long long expected = 0;
入力:
long[] dimensions = new long[] {5, 10};
期待される出力:
long expected = 0;
解説
A single matrix needs no multiplication: 0.
解き方のヒント
まずは自分で考えてから、ヒントを1つずつ開いてみましょう。
ヒント 1
The order of multiplication changes the total cost even though the final matrix shape stays the same.
ヒント 2
Try every possible split point for each interval and reuse smaller interval results.
ヒント 3
Use the dimensions array carefully: each subproblem depends on the endpoints around the matrices, not the matrix count alone.
目安の計算量
O(n^3) time, O(n^2) extra space
参考資料
この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。