B - Multiplication Puzzle POJ - 1651

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
6
10 1 50 50 20 5
Sample Output
3650
  
  
题意:
乘法游戏是在一行牌上进行的。每一张牌包括了一个正整数。在每一个移动中,玩家拿出一张牌,得分是用它的数字乘以它左边和右边的数,所以不允许拿第1张和最后1张牌。最后一次移动   后,这里只剩下两张牌。
你的目标是使得分的和最小。
例如,如果数是10 1 50 20 5,依次拿1、20、50,总分是
10*1*50+50*20*5+10*50*5=8000
而拿50、20、1,总分是
1*50*20+1*20*5+10*1*5=1150。 
 
输入格式 InputFormat
输入文件的第一行包括牌数(3<=n<=100),第二行包括N个1-100的整数,用空格分开。
 
输出格式 OutputFormat
输出文件只有一个数字:最小得分
 
 
 
一开始用的__int64 储存的,后来自己计算了下数据范围,假设全部都是100那么就是(n-2)+(100*100*100)=98000000没有超int,所以用int就可以了
思路一开始是想会不会是贪心,每次取乘积最小的,但是这么模拟一下样例都过不了
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

int n,a[105],dp[105][105],i,j,k,l;

int main()
{
    while(~scanf("%d",&n))
    {
        for(i = 1; i<=n; i++)
            scanf("%d",&a[i]);
        memset(dp,0,sizeof(dp));
        for(l = 2; l<n; l++)///区间长度从2开始枚举
        {
            for(i = 2; i+l-1<=n; i++)///区间终点
            {
                j = i+l-1;
                dp[i][j] = 100000000;
                for(k = i; k<j; k++)///枚举中点
                    dp[i][j] = min(dp[i][j],dp[i][k]+dp[k+1][j]+a[i-1]*a[k]*a[j]);
            }
        }
        printf("%d\n",dp[2][n]);
    }

    return 0;
}

 
后来就想到了区间DP
在论坛看到的解释很不错,就转在这里:
最左端和最右端的牌是不能被取走的,除这两张以外的所有牌,必然有一张最后取走。取走这最后一张牌有一个仅与它本身以及最左端和最右端的牌的值有关的得分,这个分值与其他牌没有任何关系。当这张最后被取走的牌被定下来以后(假设位置为k), 最左端到k之间的所有牌被取走时所造成的得分必然只与这之间的牌有关从而与j到最右端之间的牌独立开来。这样就构成了两个独立的子区间,出现重叠子问题。于是问题的解就是取走最后一张牌的得分+两个子区间上的最小得分不妨假设当前区间为[i, j],在(i,j)之间枚举最后一张被取走的牌,通过最优子问题求出当前区间的最优解:
        dp[i][j] = min{ dp[i][k]+dp[k][j] + a[i]*a[j]*a[k]   (i+1<=k<=j-1) }
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值