Bamboo and Artificial ZZ Test instructions:
Very straightforward, classical dynamic programming matrix chain multiplication problem
Analysis:
Matrix chain A1A2: An satisfies the binding law and can be used in parentheses to reduce the computational cost.
A matrix of P Q is multiplied by a matrix ofQR, and the cost is PQr
The features of dynamic programming are satisfied when parentheses are added
A matrix of length 1 does not require parentheses
The length >=2 matrix chain Aiai+1.....aj, bound between AK and ak+1 parentheses, divided into two groups of the respective parentheses scheme is already optimal.
M[I][J] Represents the cost of Ai-aj matrix chain multiplication, then
Core statement:
I=j m[i][j]=0;
i<j M[i][j] = min (M[i][k] + m[k+1][j] + pi-1pkPJ); I<=k<j
L: Matrix chain length, length 1 no consideration
I: and J traverse all matrix chains of length L
K: Traversal of all possible split points
Keep the minimum scheme
Output bracket scheme, S[I][J] record split point K, recursive output scheme. Note the left priority, there are two ways, you can judge if (Q<=m[i][j]) with an equal sign, or the inner layer of the K-loop reverse
Pseudo code
intP[]intM[][]intS[][]voidMultiply () {Initialization of m[][] forL =2: N fori =1: n-l+1j = I+l-1m[i][j]= INF forK = I:=j-1Q = m[i][k]+m[k+1][j]+ P[i-1]*P[K]*P[J]if(Q<=m[i][j]) m[i][j] = q S[i][j] = K End End END}voidPrint (i, j) {if(i==j) printf ("A%d"IElseprintf"(") print (I,s[i][j]) print (S[i][j]+1, j) printf (")") End}
The code is as follows:
#include <stdio.h>#include <math.h>#include <iostream>#include <cstring>#include <cmath>using namespaceStdintp[310];intm[305][305];ints[305][305];Const intINF =1<< -;voidMulity (intN) { for(inti =0; i<=n;i++) M[i][i] =0; for(intL =2; l<=n;l++) for(inti =1; i<= n-l+1; i++) {intj = I+l-1; M[i][j]= INF; for(intK = I;k<=j-1; k++) {intQ = m[i][k]+m[k+1][j]+ P[i-1]*P[K]*P[J];if(Q<=m[i][j]) {M[i][j] = q; S[I][J] = k; } } }}voidPrint (intIintj) {if(i==j) printf ("A%d", i);Else{printf ("("); Print (I,s[i][j]); Print (S[i][j]+1, j); printf")"); }}intMain () {intN while(~SCANF ("%d", &n)) { for(inti =0; i<=n;i++) scanf ("%d", &p[i]); Mulity (n); printf"%d\n", m[1][n]); Print (1, n); printf"\ n"); } }
2016-level algorithm fourth time on-machine-a.bamboo and artificial zz