-
Notifications
You must be signed in to change notification settings - Fork 5
/
matrix_chain_multi.cpp
87 lines (76 loc) · 1.63 KB
/
matrix_chain_multi.cpp
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 <iostream>
#include <cmath>
#include <climits>
/*
*STL headers
*/
#include <vector>
#include <iterator>
#include <algorithm>
#include <string>
using namespace std;
#define PN cout<<'\n'
#define PI 3.1415926535
#define MOD 1000000007
pair<int, vector<vector<int>> > matrix_chain(int n, vector<int> p){
vector<vector<int>> M, POS;
M.resize(n+1);
POS.resize(n+1);
for (int i = 0; i < n + 1; ++i){
M[i].resize(n+1);
POS[i].resize(n+1);
}
for (int i = 0; i < n + 1; ++i){
M[i][i] = 0;
POS[i][i] = -1;
}
int i, j, l, k, cost_min;
for(l = 2; l < n+1; ++l) {
for(i = 1; i < n-l+2; ++i) {
j = i+l-1;
M[i][j] = INT_MAX;
for(k = i; k < j; ++k){
cost_min = M[i][k] + M[k+1][j] + p[i-1]*p[k]*p[j];
//cout<<cost_min<<'\n';
//cout<<i<<"->"<<k<<"-->"<<j<<'\n';
if(cost_min <= M[i][j]) {
M[i][j] = cost_min;
POS[i][j] = k;
}
}
}
}
return make_pair(M[1][n], POS);
}
void print_minimum_cost_chain(vector<vector<int>> POS, int i, int j){
if (i == j){
cout<<"A"<<i;
return;
}
cout<<"(";
print_minimum_cost_chain(POS, i, POS[i][j]);
cout<<"*";
print_minimum_cost_chain(POS, POS[i][j] + 1, j);
cout<<")";
return;
}
int main()
{
int n, temp;
vector<int> p;
cout<<"Enter number of matrices--> ";
cin>>n;
p.resize(n+1);
cout<<"Enter matrix orders one by one.\n";
for(unsigned i = 0; i < n; ++i) {
cin>>p[i];
cin>>temp;
}
p[n] = temp;
pair<int, vector<vector<int>> > ans;
ans= matrix_chain(n, p);
cout<<"Minimum cost ->\t"<<ans.first<<'\n';
cout<<"Optimum Sequence of multiplication -> \t";
print_minimum_cost_chain(ans.second, 1, n);
return 0;
}