챌린지 목록으로 돌아가기
어려움 0명 해결 정답률 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

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에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.