-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMatrix Chain Multiplication
87 lines (83 loc) · 1.58 KB
/
Matrix Chain Multiplication
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <bits/stdc++.h>
#define inf 2000000000
using namespace std;
int matrix[12][2];
int dp[12][12],path[12][12];
bool visited[12][12];
int solve(int beg,int en)
{
if(beg==en)
{
path[beg][en]=beg;
return 0;
}
if(visited[beg][en])
return dp[beg][en];
visited[beg][en]=true;
int i,k=0,mx=inf;
for(i=beg;i<en;i++)
{
k=solve(beg,i)+solve(i+1,en)+matrix[beg][0]*matrix[i][1]*matrix[en][1];
if(k<mx)
{
mx=k;
path[beg][en]=i;
}
}
return dp[beg][en]=mx;
}
int print(int beg,int en)
{
if(beg>en)
return 0;
if(path[beg][en]==en)
{
if(beg==en)
{
printf("A%d",path[beg][en]);
}
else
{
printf("(");
int i=0;
while(beg<=en)
{
if(i)
printf(" x ");
else
i=1;
printf("A",path[beg][en]);
beg++;
}
printf(")");
}
}
else
{
printf("(");
print(beg,path[beg][en]);
printf(" x ");
print(path[beg][en]+1,en);
printf(")");
}
return 0;
}
int main()
{
int i,j,n,cs=0;
//freopen("out.txt","w",stdout);
while(cin>>n&&n)
{
cs++;
for(i=1;i<=n;i++)
{
cin>>matrix[i][0]>>matrix[i][1];
}
memset(visited,false,sizeof(visited));
solve(1,n);
printf("Case %d: ",cs);
print(1,n);
printf("\n");
}
return 0;
}