(POJ 1651)Multiplication Puzzle 区间DP (dp思路总结)

来源:互联网 发布:win10开机优化策略 编辑:程序博客网 时间:2024/05/29 07:44

Multiplication Puzzle
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 8806 Accepted: 5516
Description

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
Source

Northeastern Europe 2001, Far-Eastern Subregion

DP总结:
这里写图片描述
这里写图片描述

区间DP总结:
这里写图片描述

题意:
有n张牌,每张牌是一个整数,除了左右端的两张牌外要拿走所有的牌,拿牌第i张牌的代价为a[i-1]*a[i]*a[i+1],问拿完中间所有的牌的最小代价为多少?

分析:
由于我是经过kungbin的区间DP训练里来做这题的,所以我已经知道了是一道区间DP的题。不过我们还是可以推出来的:

首先通过简单的样例来找规律:
n = 3
50 10 50
所以代价为 50*10*50;
n = 4
50 20 10 50
我们有两种取法: 20,10 或 10 ,20。当我们以20,10的顺序取时,代价为50*20*10 + “50 10 50”的取法,“50 10 50”是一个n = 3的子问题。
所以我们由此可以想到是区间DP的问题。
设dp[i][j] 表示 取完第i~j个数的最小代价,k表示最后取出的是第k个数,所以
dp[i][j] = min(dp[i][k]+dp[k][j]+a[i]*a[k]*a[j])

AC代码:

#include <iostream>#include <cstdio>#include <cstring>#include <string>#include <algorithm>#include <cmath>using namespace std;int dp[110][110],a[110];int solve(int i,int j){    if(dp[i][j] != -1) return dp[i][j];    if(j == i+1) return dp[i][j] = 0;    int ans = 999999999;    for(int k=i+1;k<j;k++)        ans = min(ans,solve(i,k)+solve(k,j)+a[i]*a[k]*a[j]);    return dp[i][j]=ans;}int main(){    int n;    while(scanf("%d",&n)!=EOF)    {        for(int i=1;i<=n;i++)            scanf("%d",&a[i]);        memset(dp,-1,sizeof(dp));        printf("%d\n",solve(1,n));    }    return 0;}
1 0
原创粉丝点击