动态规划之划分动态规划:矩阵链乘 poj 1651 Multiplication Puzzle

来源:互联网 发布:加入淘宝要多少钱 编辑:程序博客网 时间:2024/06/01 08:35

题意:给你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

610 1 50 50 20 5

Sample Output

3650

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>using namespace std;#define ll __int64#define inf 0x7ffffffll 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;}


0 0
原创粉丝点击