Poj 1651 Multiplication Puzzle

Multiplication Puzzle

Time Limit: 1000MS

 

Memory Limit: 65536K

Total Submissions: 4948

 

Accepted: 2958

Description

The multiplication puzzle is played with arow of cards, each containing a single positive integer. During the move playertakes one card out of the row and scores the number of points equal to theproduct of the number on the card taken and the numbers on the cards on theleft and on the right of it. It is not allowed to take out the first and thelast 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 ofscored points. 

For example, if cards in the row contain numbers 10 1 50 20 5, player mighttake 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, thescore would be 

1*50*20 + 1*20*5 + 10*1*5 = 1000+100+50 =1150.

Input

The first line of the input contains thenumber of cards N (3 <= N <= 100). The secondline contains N integers in the range from 1 to 100, separated by spaces.

Output

Output must contain a single integer - theminimal score.

Sample Input

6

10 1 50 50 20 5

Sample Output

3650


对于卡片a[0],a[1],...,a[n-1],假设存在不连续的三张卡片i,j,k,在卡片序列i,i+1,i+2,...,j-1,j,j+1,...,k-1,k,k+1,...中,取走i,j之间卡片,可得得分d[i][j],同理拿走j,k之间卡片,可得得分d[j][k],当只剩i,j,k三张时,易知d[i][k]=d[i][j]+d[j][k]+a[i]*a[j]*a[k];则dp方程得出。

对长度由1-n的区间分别遍历,得到所有长度的所有区间的值,并在相同区间内取最小值作为该区间的分数,最后得出d[1][n-1];

下面是代码:

#include <algorithm>
#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <cstdio>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
using namespace std;
#define Max 200005

int a[105],d[105][105];

int solve(int n){
    memset(d, 0, sizeof(d));
    for (int len=1; len<n; len++) {
        for (int i=1,j=i+len; j<n; j++,i++) {
            int min=1000000000;
            for (int k=i; k<j; k++) {
                int count=d[i][k]+d[k+1][j]+a[i-1]*a[k]*a[j];
                if (count<min) {
                    min=count;
                }
            }
            d[i][j]=min;
        }
    }
    return d[1][n-1];
}

int main(){
    int n;
    long long sum=0;
    while (cin>>n) {
        for (int i=0; i<n; i++) {
            cin>>a[i];
        }
        cout<<solve(n)<<endl;
    }
    
    return 0;
}


你可能感兴趣的:(Poj 1651 Multiplication Puzzle)