《算法》P49
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include<string.h> 4 //int m[102][102], s[102][102]; 5 void MatrixChain(int *p, int n, int m[][102], int s[][102]) 6 { 7 for(int i = 1; i <= n; i ++) 8 m[i][i] = 0; 9 for(int r = 2; r <= n; r ++){ 10 for(int i = 1; i <= n - r + 1; i ++){ 11 int j = i + r - 1; 12 m[i][j] =m[i][i] + m[i + 1][j] + p[i - 1] * p[i] * p[j]; 13 s[i][j] = i; 14 for(int k = i + 1; k < j; k ++){ 15 int t = m[i][k] + m[k + 1][j] + p[i - 1] *p[k] * p[j]; 16 if(t < m[i][j]){ 17 m[i][j] = t; 18 s[i][j] = k; 19 } 20 } 21 } 22 } 23 } 24 static int recl[102], recr[102]; 25 void Traceback(int i, int j, int m[][102], int s[][102]) 26 { 27 if(i == j) return; 28 Traceback(i, s[i][j], m, s); 29 Traceback(s[i][j] + 1, j, m, s);//printf("Multiply A%d, %d and A%d , %d\n", i, s[i][j], s[i][j] + 1, j); 30 recl[i] ++; 31 recr[j] ++; 32 } 33 int main() 34 { 35 int m[102][102], s[102][102]; 36 int p[105], N; //int *mm = &m[0][0], *ss = &s[0][0]; 37 scanf("%d" ,&N); 38 for(int i = 0; i <= N; i ++) 39 scanf("%d", &p[i]); 40 MatrixChain(p, N, m, s); 41 42 Traceback(1, N, m, s); 43 printf("%d\n", m[1][N]); 44 int flag = 0; 45 46 if(recl[1] == 0){ 47 printf("("); 48 flag = 1; 49 } 50 for(int i = 1; i <= N; i ++){ 51 while(recl[i]--) 52 printf("("); 53 printf("A%d", i); 54 while(recr[i]--) 55 printf(")"); 56 if(flag == 1) 57 printf(")"); 58 } 59 printf("\n"); 60 system("pause"); 61 return 0; 62 }