問題
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
最終的な行列サイズは同じでも、掛ける順番で総コストは変わります。
ヒント 2
各区間についてすべての分割点を試し、小さい区間の結果を再利用します。
ヒント 3
dimensions 配列は慎重に扱います。各部分問題は行列数だけでなく、その両端の次元に依存します。
目安の計算量
時間 O(n^3)、追加メモリ O(n^2)
参考資料
この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。