This repository was archived by the owner on Sep 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatrixchain.java
More file actions
45 lines (35 loc) · 1.27 KB
/
matrixchain.java
File metadata and controls
45 lines (35 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.awt.Point;
import java.util.*;
public class matrixchain {
static Point[] matricies;
static Long[][] memo;
public static void main(String[] args) {
/*
* matricies = new Matrix[]{ new Matrix(200, 100), new Matrix(100, 2),
* new Matrix(2, 30), new Matrix(30, 20), new Matrix(20, 200), new
* Matrix(200, 1000), new Matrix(1000, 4), new Matrix(4, 2), new
* Matrix(2, 1), new Matrix(1, 1), new Matrix(1, 10) };
*/
matricies = new Point[] { new Point(8, 2), new Point(2, 4), new Point(4, 1) };
memo = new Long[matricies.length][matricies.length];
long result = go(0, matricies.length - 1);
System.out.println(result);
}
static Long go(int i, int j) {
if (i == j)
return 0L;
if (memo[i][j] != null)
return memo[i][j];
long bestCost = Long.MAX_VALUE;
// Split on parenthesis [i,k] and [k+1,j]
for (int k = i; k < j; k++) {
int A = matricies[i].x;
int B = matricies[k].y;
int C = matricies[j].y;
long curCost = go(i, k) + go(k + 1, j) + A * B * C;
bestCost = Math.min(bestCost, curCost);
}
memo[i][j] = bestCost;
return bestCost;
}
}