Title: n matrix multiplication, to find the least number of multiply operations and how to combine
Suppose that matrix A is r1*r2 and matrix B is R2*R3, so m=a*b=r1*r2*r3. When multiple matrices are multiplied, the number of operations is different when the matrix is combined in different ways.
Example: M=M1 * M2 * M3 * M4
[5*20] [20*50] [50*1] [1*100]
((m1*m2) *m3) *m4=5000+250+500=5750
and M1* (m2* (M3*M4)) =5000+100000+10000=115000
If you follow (m1* (M2*M3) *m4) =1000+100+500=1600
The above example shows that the number of operations is different depending on the binding sequence. Now we are asking for the least number of multiplication operations to be performed in which order, and to find out the minimum number of operations.
Algorithm idea:
Remember MI*MI+1*MI+2*...*MJ is mij, the size of the matrix is: M1 for r1*r2,m2 r2*r3,m3 for R3*R3,M4 for R4*R5. R1,R2,R3,R4,R5 are 5,20,50,1,100 respectively.
(1) The first calculation of the matrix multiplication of 2 3 cases.
m12=m1*m2=r1*r2*r3=5000,m23=r2*rr*r4,m34=r3*r4*r5=1000,m34=5000
(2) 2 cases where the number of multiply matrices is calculated as 3
M13=M1*M2*M3, the goal is to find the minimum number of multiplication operations for M13. m13=min{m1*m23+r1*r2*r4,m12*m3+r1*r3*r4}=min{1100,5250}=m12*m3+r1*r3*r4=1100
similarly m24=m2*m3*m4=min{m2*m34+r2*r3*r,m23*m4+r2*r4*r5}=min{10500,3000}=3000;
(3) The final result of calculating the number of multiply matrices is 4:
M14=min (M13*M4+R1*R4*R5,M12*M34+R1*R3*R4,M1*M24+R1*R2*R5) ={3000+10000, 5000+5000,+25000,1100+500}=1600
The algorithm is as follows
1#include <iostream>2 3 using namespacestd;4 5 intr[ -],com[ -][ -];6 7 intCourseintIintj)8 {9 intu,t;Ten if(i==j) One return 0; A if(i==j-1) - { -com[i][j]=i; the returnr[i]*r[i+1]*r[i+2]; - } - Else - { +U=course (i,i) +course (i+1, j) +r[i]*r[i+1]*r[j+1]; -com[i][j]=i; + for(intk=i;k<j;k++) A { atT=course (I,k) +course (k +1, j) +r[i]*r[k+1]*r[j+1]; - if(t<u) - { -u=T; -com[i][j]=K; - } in } - returnu; to } + } - the * intMain () $ {Panax Notoginseng intN; -printf"Input N:"); thescanf"%d",&n); + for(intI=1; i<=n;i++) Ascanf"%d",&r[i]); theprintf"min=%d\n", Course (1, N-1)); + for(intI=1; i<=n;i++) - { $ for(intj=1; j<=n;j++) $printf"%d", Com[i][j]); -printf"\ n"); - } the return 0; -}
COM is suitable for com[i][j]=k, which is used to preserve the combination of matrices, which represents the least number of times to multiply when mik*mkj.
The procedure for recursive invocation is as follows:
1-2,2-3,3-4 and other sub-problems are recursively called 2 times, the sub-problem exists duplicate. You can use the memo method to solve the problem, set a global variable m[i][j[, store the value of the computed course (I,J), and then make the next call directly.
Matrix multiplication of dynamic programming