LCS
Time Limit: 1000ms
Memory Limit: 128M
Description:
已知有n個矩陣,第i個矩陣的行數爲a[i], 列數爲a[i+1]。
試求把n個矩陣乘起來所需要的執行乘法的次數的最小值。
Input:
第一行是一個正整數n,表示矩陣的個數。
第二行有n+1個整數,第i個整數表示a[i]。
Output:
輸出第一行有一個整數,將n個矩陣乘起來所要執行的乘法次數的最小值。
Sample Input:
4
1 2 3 4 5
Sample Output:
38
Hint:
對於80%的數據 n <= 100
對於100%的數據 n <= 2000, a[i] <= 100
#include<iostream>
using namespace std;
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
int p[n],m[n+1][n+1];
for(int i=0;i<=n;i++)
{
scanf("%d",&p[i]);
}
for(int i=1;i<=n;i++)m[i][i]=0;
for(int r=2;r<=n;r++)
{
for(int i=1;i<=n-r+1;i++)
{
int j=i+r-1;
m[i][j]=m[i+1][j]+p[i-1]*p[i]*p[j];
for(int k=i+1;k<j;k++)
{
int t=m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j];
if(t<m[i][j])
{
m[i][j]=t;
}
}
}
}
cout<<m[1][n]<<endl;
}
return 0;
}