Description
On the way back from the algorithm class, you are still amazed by the beauty of DP.
The so-called thinking of the day, night dream, noon is no exception. Because the research DP is too invested, you had a strange dream during the nap.
In this dream, you have returned to the 19th century. At that time, people had no concept of computers. Unfortunately, you have taken your notebook during a time-space trip. So naturally, you became one of the greatest scientists of that age.
On this day, you have a gathering with a group of fellow scientists. The question of matrix chain multiplication was discussed. At that time, there was no good solution. And you think of the dynamic planning method just mentioned in the algorithm class (why ?? It should be a long time later ......).
PS: For matrix chain multiplication problems, see Chapter 15th introduction to algorithms section 2nd.
-
Input
-
The first row has only one integer N, indicating the number of matrix chains.
Each matrix chain is described as follows:
The first row is an integer m (0 <m <= 100 ). Indicates a total of M matrices
In the next m row, each line contains an integer of PI and Qi (0 <Pi, Qi <= 100 ). Indicates the dimension of matrix AI.
Input data ensures matrix compatibility.
-
Output
-
Each matrix chain outputs two rows.
The first line is an integer that represents the minimum number of scalar multiplication.
The second line uses brackets to describe this method.
When the optimal solution is not unique, multiply by the order of first left and right.
For example, there are three matrices A1, A2, and A3. When (a1a2) A3) and (A1 (a2a3) are equal, output (a1a2) A3 ).
-
Sample Input
-
1630 3535 1515 55 1010 2020 25
-
Sample output
-
15125((A1(A2A3))((A4A5)A6))
Introduction to algorithms and Dynamic Planning
#include<iostream>using namespace std;void comeon(int a[110][110],int l,int r){if(l==r)cout<<"A"<<l+1;else if(l==r-1)cout<<"(A"<<l+1<<"A"<<r+1<<")";else {cout<<"(";comeon(a,l,a[l][r]);comeon(a,a[l][r]+1,r);cout<<")";}}int main(){int t,n,i,j,k,m,a[1100][2],d[110][110],hai[110][110]={0};cin>>t;while(t){cin>>n;for(i=0;i<n;i++)cin>>a[i][0]>>a[i][1];for(i=0;i<n;i++)d[i][i]=0;for(k=1;k<n;k++)for(i=0;i<n-k;i++){d[i][i+k]=d[i][i]+a[i][0]*a[i][1]*a[i+k][1]+d[i+1][i+k];hai[i][i+k]=i;for(j=i+1;j<i+k;j++){m=d[i][j]+a[i][0]*a[j][1]*a[i+k][1]+d[j+1][i+k];if(d[i][i+k]>=m){d[i][i+k]=m;hai[i][i+k]=j;}}}cout<<d[0][n-1]<<endl;comeon(hai,0,n-1);cout<<endl;//for(i=0;i<n;i++)//{//for(j=0;j<n;j++)cout<