题解POJ1651Multiplication Puzzle

Posted xsl19

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了题解POJ1651Multiplication Puzzle相关的知识,希望对你有一定的参考价值。

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

Solution

题意简述:给定一个序列,取走一个数的代价是它乘上它相邻的两个数,两头的数不能取,求最小代价。

考虑区间DP。

\(dp[i][j]\)表示把\(i+1\)~\(j-1\)的数都取走的最小代价。

然后进行区间DP,注意区间的长度的范围是\(3\)~\(n\)

状态转移方程:

\[dp[i][j]=min(dp[i][j], dp[i][k] + dp[k][j] + a[i] * a[j] * a[k])\]

Code

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cctype>

using namespace std;

inline int gi()

    int f = 1, x = 0; char c = getchar();
    while (c < '0' || c > '9')  if (c == '-') f = -1; c = getchar();
    while (c >= '0' && c <= '9')  x = x * 10 + c - '0'; c = getchar();
    return f * x;


int n, m, dp[103][103], a[103];

int main()

    memset(dp, 0, sizeof(dp));//初始化
    n = gi();
    for (int i = 1; i <= n; i++) a[i] = gi();
    for (int i = 3; i <= n; i++)//枚举区间长度
    
        for (int j = 1; j + i <= n + 1; j++)//枚举起点
        
            int k = j + i - 1;//终点
            dp[j][k] = 1000000007;//当前区间的dp数组初始化
            for (int l = j + 1; l <= k - 1; l++)//枚举分割点
            
                dp[j][k] = min(dp[j][k], dp[j][l] + dp[l][k] + a[j] * a[k] * a[l]);//进行状态转移
            
        
    
    printf("%d\n", dp[1][n]);//最后输出答案
    return 0;//结束

以上是关于题解POJ1651Multiplication Puzzle的主要内容,如果未能解决你的问题,请参考以下文章

POJ 1651 - Multiplication Puzzle - [区间DP]

POJ 1651 Multiplication Puzzle

POJ - 1651 Multiplication Puzzle

poj-1651-Multiplication Puzzle--区间DP

POJ 1651 Multiplication Puzzle (区间DP)

Multiplication Puzzle POJ - 1651