Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 27ebeb6

Browse files
Add function to print parantheses
1 parent f5037d2 commit 27ebeb6

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

‎matrix_chain.cpp

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,26 @@
11
#include <bits/stdc++.h>
2+
#define N 10
23
using namespace std;
34

5+
int dp[N][N], parans[N][N];
6+
7+
void printParans(int i, int j) {
8+
if(i+1 == j) {
9+
cout<<char('A'+i-1)<<char('A'+i);
10+
return;
11+
}
12+
if(i == j) {
13+
cout<<char('A'+i-1);
14+
return;
15+
}
16+
cout<<'(';
17+
printParans(i,parans[i][j]);
18+
cout<<")(";
19+
printParans(parans[i][j]+1,j);
20+
cout<<')';
21+
}
22+
423
void matrixMult(int dimensions[], int n) {
5-
int dp[n][n];
624
int i,j,k,l;
725

826
for(i=1; i<n; i++) {
@@ -14,12 +32,16 @@ void matrixMult(int dimensions[], int n) {
1432
dp[i][j] = INT_MAX;
1533
for(k=i; k<=j-1; k++) {
1634
int cost = dp[i][k] + dp[k+1][j] + dimensions[i-1]*dimensions[k]*dimensions[j];
17-
if(cost < dp[i][j])
35+
if(cost < dp[i][j]) {
1836
dp[i][j] = cost;
37+
parans[i][j] = k;
38+
}
1939
}
2040
}
2141
}
2242
cout<<"Min cost : "<<dp[1][n-1]<<endl;
43+
printParans(1,n-1);
44+
cout<<endl;
2345
}
2446

2547
int main() {

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /