矩阵链乘,状态转移方程:dp(i,j)=min{dp(i,k)+dp(k+1,j)+a[i]*b[j]*b[k]}。这个题目主要就是要记录路径。做了那个ZOJ1463之后,这个应该不成问题。
下面贴代码:
View Code
1 #include <iostream> 2 using namespace std; 3 int dp[11][11],c[11][11],a[11],b[11],num; 4 void printans(int i,int j) 5 { 6 if(i == j) 7 { 8 cout<<"A"<<i; 9 } 10 if(i < j) 11 { 12 cout<<"("; 13 printans(i,c[i][j]); 14 cout<<" x "; 15 printans(c[i][j] + 1,j); 16 cout<<")"; 17 } 18 } 19 int main() 20 { 21 int i,j,p,k,temp,ncase = 1; 22 while(cin>>num) 23 { 24 if(num == 0) 25 break; 26 for(i = 1;i <= num;i++) 27 cin>>a[i]>>b[i]; 28 for(i = 1;i <= num;i++) 29 for(j = 1;j <= num;j++) 30 { 31 if(i == j) 32 dp[i][j] = 0; 33 else 34 dp[i][j] = 1<<30; 35 c[i][j] = i; 36 } 37 for(p = 1;p <= num - 1;p++) 38 { 39 for(i = 1;i <= num - p;i++) 40 { 41 j = i + p; 42 for(k = i;k <= j;k++) 43 { 44 temp = dp[i][k] + dp[k + 1][j] + a[i] * b[k] * b[j]; 45 if(temp < dp[i][j]) 46 { 47 dp[i][j] = temp; 48 c[i][j] = k; 49 } 50 } 51 } 52 } 53 cout<<"Case "<<ncase<<": "; 54 printans(1,num); 55 cout<<endl; 56 ncase++; 57 }//while 58 return 0; 59 }