Skip to content

Instantly share code, notes, and snippets.

@abrarShariar
Created November 16, 2016 04:33
Show Gist options
  • Select an option

  • Save abrarShariar/d558a1a36d1868da04c0386d172023f4 to your computer and use it in GitHub Desktop.

Select an option

Save abrarShariar/d558a1a36d1868da04c0386d172023f4 to your computer and use it in GitHub Desktop.
lab work algo MCM
#include<iostream>
using namespace std;
void Matrix_Chain_Order(int*,int);
int S[100][100];
void print_s(int i,int j){
if(i == j){
cout<<"A"<<i;
}else{
cout<<"(";
print_s(i,S[i][j]);
print_s(S[i][j]+1,j);
cout<<")";
}
}
int main(){
//int d[] = {10,15,20,25,30}; //array of matrix sizes d
//int n= sizeof(d)/sizeof(d[0]) - 1;
int sz;
cout<<"SZ: ";
cin>>sz;
int d[sz];
for(int i=0;i<sz;i++){
cin>>d[i];
}
int n = sizeof(d)/sizeof(d[0]) - 1;
Matrix_Chain_Order(d,n);
}
void Matrix_Chain_Order(int* d,int n){
int M[n+1][n+1];
//int S[n+1][n+1];
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
M[i][j]= -1;
S[i][j] = 0;
}
}
//initializing diagonal elements with 0
for(int i=1;i<=n;i++){
M[i][i] = 0;
}
for(int len = 2;len <= n;len++){
for(int i = 1;i <= n-len+1;i++){
int j = i+len-1;
M[i][j] = 9999999;
for(int k = i;k <= j-1;k++){
int q = M[i][k] + M[k+1][j] + (d[i-1] * d[k] * d[j]);
if(q < M[i][j]){
M[i][j] = q;
//s goes here
S[i][j] = k;
}
}
}
}
//test print
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cout<<M[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
int i = 1;
int j = 1;
//print_s(S[][5],i,j);
/*
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cout<<S[i][j]<<" ";
}
cout<<endl;
}
*/
print_s(1,4);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment