1. 程式人生 > >動態規劃之劃分動態規劃:矩陣鏈乘 poj 1651 Multiplication Puzzle

動態規劃之劃分動態規劃:矩陣鏈乘 poj 1651 Multiplication Puzzle

題意:給你n個數,進行如下操作,問最小值

             For example, if cards in the row contain numbers 10 1 50 20 5, player might take a card with 1, then 20 and 50, scoring 
10*1*50 + 50*20*5 + 10*50*5 = 500+5000+2500 = 8000

If he would take the cards in the opposite order, i.e. 50, then 20, then 1, the score would be 
1*50*20 + 1*20*5 + 10*1*5 = 1000+100+50 = 1150.

分析:矩陣鏈乘模板題

m[i, j]= min i <= k <j  { m[i, k] + m[k+1, j] + p i-1  p k  p j };

Sample Input

6
10 1 50 50 20 5

Sample Output

3650

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll __int64
#define inf 0x7ffffff
ll a[111],dp[111][111];
int main()
{
	ll n;
	scanf("%I64d",&n);
	int i,l,j,k;
	ll q;
	for(i=0;i<n;i++) scanf("%I64d",&a[i]);
	for(i=1;i<=n;i++) dp[i][i]=0;
	for(l=2;l<=n-1;l++)
	{
		for(i=1;i<=n-l;i++)
		{
			j=i+l-1;
			dp[i][j]=inf;
			for(k=i;k<=j-1;k++){
				q=dp[i][k]+dp[k+1][j]+a[i-1]*a[k]*a[j];
				if(q<dp[i][j]) dp[i][j]=q;
			}
		}
	}
	printf("%I64d\n",dp[1][n-1]);
	return 0;
}