すべてのチャレンジ
難しい 1件解決済み 正答率100.0%

Matrix Chain Multiplication

Find the cheapest order to multiply a chain of matrices.

このチャレンジで学べること

  • Define DP over subchains
  • Try every split point
  • Minimize multiplication cost

問題

翻訳を表示

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

例

例 1
入力:
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.

例 2
入力:
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用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

# コーダー 言語 時間 メモリ AI 評価 解答
1 Н"Никита "Programmer" Python 777 ms - 5/5 コードを見る

他の人の解答から学ぶ

コミュニティの解答

ネタバレ注意: この下に解答が1件あります まずは自分で挑戦してみましょう。他の開発者のコードやAIレビューも見ることができます。 サインインして課題を解くと議論に参加できます。