ronith
10/26/2018 - 9:27 AM

Printing brackets in Matrix Chain Multiplication

#include <bits/stdc++.h>
using namespace std;

void print( int *a, int i, int j,int n, char &name) {
    if (i==j) {
        cout<< name++;
        return;
    }
    cout<< "(";
    print (a, i,*((a+i*n)+j),n, name );
    print (a, *((a+i*n)+j)+1, j,n, name);
    cout<< ")";
}

int main() {
    int n;
    cin>>n;
    int a[n];
    for (int i=0;i<n;i++)
        cin>> a[i];

    int brackets[n][n];
    int dp[n][n];
    for (int i=0;i<n;i++)
        dp[i][i]= 0;

    for (int len=2; len<n;len++) {
        for (int i=1;i<=n-len; i++) {
            int j= i+len-1;
            dp[i][j]= INT_MAX;
            for (int k=i;k<j;k++) {
                int m= dp[i][k]+dp[k+1][j]+a[i-1]*a[k]*a[j];
                if (dp[i][j]>m) {
                    dp[i][j]= m;
                    brackets[i][j]= k;
                }
            }
        }
    }
    cout<< dp[1][n-1];
    char name= 'A';
    print ((int*)brackets, 1, n-1,n, name);
}