POJ 1651—Multiplication Puzzle (Interval dp)


Multiplication Puzzle
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 8604   Accepted: 5375

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

The general meaning of the title is:
an integer sequence contains N integers from 1 to 100 (3<=N<=100), take a number from it and multiply it with the integers on the adjacent two sides, and proceed in turn until only the first and last two are left. Find the minimum value of the final sum. The numbers on both sides cannot be selected, and the selection is not repeated.
The following is the idea I understand from it:
dp[i][j] represents the sum obtained by taking the numbers between the ith and the jth, then the width of the subsequence determined by the number represented by k, in turn Increase the width and move the subsequence, that is, change the value of i, then traverse the elements between i and i+k, compare dp[i][i+k] and select a[i] and a[j] first The number between, the number between a[j] and a[i+k], and finally only a[j] is left, the sum dp[i][j]+dp[j] obtained in this process The size of [i+k]+a[i]*a[i+k]*a[j] and the original sum.

#include<stdio.h>
#include<string.h>
#define min(a,b) ((a)<(b)?(a):(b))
int dp[110][110];
int main(void)
{
    int i,j,k,a[110];
    int n;
    scanf("%d",&n);
    for(i=1;i<=n;i++)
        scanf("%d",&a[i]);
    for(k=2;k<=n;k++)
        for(i=1;i+k<=n;i++)
        {
            dp[i][i+k]=10000000;设dp[i][k+i]的初值很大,
            for(j=i+1;j<i+k;j++)
                dp[i][i+k]=min(dp[i][i+k],dp[i][j]+dp[j][i+k]+a[i]*a[i+k]*a[j]);
        }
    printf("%d\n",dp[1][n]);
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324575906&siteId=291194637