File tree Expand file tree Collapse file tree 1 file changed +66
-0
lines changed
DP/MatrixChain_multiplication Expand file tree Collapse file tree 1 file changed +66
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ using namespace std ;
3
+ int n=0 ;
4
+ int val[100000 ];
5
+ int m=1000000 ;
6
+ int mx[1000 ][1000 ];
7
+ void print (int x,int y)
8
+ {
9
+ if (x==y)
10
+ {
11
+ cout<<x-1 ;
12
+ }
13
+ else
14
+ {
15
+ cout<<" (" ;
16
+ print (x,mx[y][x]);
17
+ print (mx[y][x]+1 ,y);
18
+ cout<<" )" ;
19
+
20
+ }
21
+
22
+ }
23
+
24
+ void fun ()
25
+ {
26
+
27
+ for (int i=0 ;i<=n;i++)
28
+ mx[i][i]=0 ;
29
+ for (int x=2 ;x<n;x++)
30
+ {
31
+ for (int j=1 ;j<n-x+1 ;j++)
32
+ {
33
+ int i=j+x-1 ;
34
+ mx[j][i]=m;
35
+ for (int k=j;k<i;k++)
36
+ {
37
+
38
+ int w=mx[j][k]+mx[k+1 ][i]+val[j-1 ]*val[k]*val[i];
39
+ if (w<mx[j][i])
40
+ {
41
+ mx[i][j]=k;
42
+ mx[j][i]=min (mx[j][i],w);
43
+ }
44
+ }
45
+
46
+
47
+
48
+ }
49
+ }
50
+ print (1 ,n-1 );
51
+ cout<<endl;
52
+ cout<<mx[1 ][n-1 ]<<endl;
53
+
54
+ }
55
+
56
+ int main () {
57
+
58
+ cin>>n;
59
+
60
+ for (int i=0 ;i<n;i++)
61
+ {
62
+ cin>>val[i];
63
+ }
64
+ fun ();
65
+ return 0 ;
66
+ }
You can’t perform that action at this time.
0 commit comments