POJ 1651 Multiplication Puzzle(区间dp)

来源:互联网 发布:高级排序算法 编辑:程序博客网 时间:2024/06/07 06:00

The multiplication puzzle is played with a row of cards, each containing a single positive integer. During the move player takes one card out of the row and scores the number of points equal to the product of the number on the card taken and the numbers on the cards on the left and on the right of it. It is not allowed to take out the first and the last card in the row. After the final move, only two cards are left in the row. 

The goal is to take cards in such order as to minimize the total number of scored points. 

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.
Input
The first line of the input contains the number of cards N (3 <= N <= 100). The second line contains N integers in the range from 1 to 100, separated by spaces.
Output
Output must contain a single integer - the minimal score.
Sample Input
610 1 50 50 20 5
Sample Output
3650

 【题解】 

 大致题意: 从给定的序列中划去数,首尾元素不能划去,每划去一个数 a[i],得分是就是 a[i-1]*a[i]*a[i+1],当序列只剩下两个数时结束,问最小得分是多少。

 

 分析:

 区间问题,dp[i][j]表示区间i到j的最小得分,则有转移方程:dp[i][j]=min(dp[i][j] , dp[i][k]+dp[k][j]+a[i]*a[k]*a[j]);

 

 【AC代码】

 

#include<iostream>#include<cstdio>#include<algorithm>#include<cstring>using namespace std;const int N=200;int a[N];int dp[N][N];int m,n;int main(){    while(~scanf("%d",&m))    {        for(int i=1;i<=m;++i)            scanf("%d",&a[i]);        memset(dp,0,sizeof(dp));        for(int i=2;i<m;++i)        {            for(int j=1;j<=m-i;++j)            {                int k=i+j;                for(int l=j+1;l<k;++l)                {                    int t=dp[j][l]+dp[l][k]+a[j]*a[l]*a[k];                    if(!dp[j][k]||dp[j][k]>t) dp[j][k]=t;//这里注意处理得当                }            }        }        printf("%d\n",dp[1][m]);    }    return 0;}

原创粉丝点击