forked from goyalavishi/Practice-Questions-Cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
avishi_matrix.cpp
75 lines (65 loc) · 1.44 KB
/
avishi_matrix.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
//matrix multiplication
#include<iostream>
#include<fstream>
#include<climits>
using namespace std;
//Print output
void printoutput(fstream& infile,int i,int j,int n,int s[], int &t)
{
if(i==j)
{
infile<<'A'<<t;
t++;
return;
}
infile<<"(";
printoutput(infile,i,s[n*i+j],n,s,t);
printoutput(infile,s[n*i+j]+1,j,n, s,t);
infile<<")";
}
//Ordering matrix
void matrixorder(fstream& infile,int arr[], int n)
{
int cost[n][n];
int s[n][n];
for (int i=1;i<n;i++)
cost[i][i]=0;
for (int l=2;l<n;l++)
{
for (int i=1;i<n-l+1;i++)
{
int j=i+l-1;
cost[i][j]=INT_MAX;
for (int k=i;k<=j-1;k++)
{
int c=cost[i][k]+cost[k+1][j]+arr[i-1]*arr[k]*arr[j];
if (c<cost[i][j])
{
cost[i][j]=c;
s[i][j]=k;
}
}
}
}
int t=1;
printoutput(infile,1,n-1,n,(int *)s,t);
}
int main(int argc,char *argv[])
{
int arr[1000];
fstream infile;
infile.open(argv[1],ios::in);
int i=0;
while(infile)
{
infile>>arr[i];
i++;
}
infile.close();
int n=i-1;
fstream outfile;
outfile.open(argv[2],ios::out);
matrixorder(outfile,arr,n);
outfile.close();
return 0;
}