POJ - 1651 Multiplication Puzzle(區間dp)

題目描述:https://vjudge.net/contest/374535#problem/E
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
10150+50205+10505=500+5000+2500=800010*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
15020+1205+1015=1000+100+50=1150.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

翻譯:
有n個數字排成一行,按一定次序從中拿走n-2個數字(第1個和最後1個數字不能拿),每次只拿一個,取走數字的同時,會得到一個分數。
分數的計算方法是:要拿走的數字,和它左右兩邊的數字,這3個數字的乘積
按不同的順序取走n-2個數字,得到的總分可能不相同,求出給定一組數字按上述規則拿取的最小得分

分析:
dp[i,j]dp[i,j]:區間[i,j],假設有m個數,刪除m-2個數的最小价值

區間dp最核心的兩層for枚舉所有的區間,第三層for循環枚舉斷點

完整代碼:

#include<cstdio>
#include<cstring>
#include<math.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
typedef long long LL;
const int N=1e2+10;
const int inf=0x3f3f3f3f;
LL dp[N][N];
int a[N],n;
int main()
{
    scanf("%d",&n);
    for(int i=1; i<=n; i++)
        scanf("%d",&a[i]);
    memset(dp,0,sizeof(dp));
    for(int i=2; i<=n; i++)
    {
        for(int j=1; j+i<=n; j++) ///因爲不能刪除兩端的數,所以區間長度最短爲2
        {
            dp[j][j+i]=inf;
            for(int k=j+1; k<j+i; k++)
                dp[j][j+i]=min(dp[j][j+i],(LL)dp[j][k]+dp[k][j+i]+a[j]*a[k]*a[j+i]);
        }
    }
    printf("%lld\n",dp[1][n]);
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章