Retour aux défis
Difficile 0 résolus 0 % de réussite

Matrix Chain Multiplication

Find the cheapest order to multiply a chain of matrices.

Ce que vous allez apprendre

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

Problème

Afficher la traduction

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.

Contraintes

2 ≤ length of dimensions ≤ 200; 1 ≤ each size ≤ 500

Exemples

Exemple 1
Entrée :
dimensions = [10, 30, 5, 60]

Sortie attendue :
expected = 4500
Entrée :
std::vector<long long> dimensions = {10, 30, 5, 60};

Sortie attendue :
long long expected = 4500;
Entrée :
long[] dimensions = new long[] {10, 30, 5, 60};

Sortie attendue :
long expected = 4500;

Explication

(A×B)×C costs 10·30·5 + 10·5·60 = 4500, cheaper than A×(B×C) = 27000.

Exemple 2
Entrée :
dimensions = [5, 10]

Sortie attendue :
expected = 0
Entrée :
std::vector<long long> dimensions = {5, 10};

Sortie attendue :
long long expected = 0;
Entrée :
long[] dimensions = new long[] {5, 10};

Sortie attendue :
long expected = 0;

Explication

A single matrix needs no multiplication: 0.

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

The order of multiplication changes the total cost even though the final matrix shape stays the same.

Indice 2

Try every possible split point for each interval and reuse smaller interval results.

Indice 3

Use the dimensions array carefully: each subproblem depends on the endpoints around the matrices, not the matrix count alone.

Complexité attendue

O(n^3) time, O(n^2) extra space

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.