poj1651 Multiplication Puzzle(区间DP)

来源:互联网 发布:网络攻防技术技能试卷 编辑:程序博客网 时间:2024/06/07 20:02

题意:给出一串数字,第一个和最后一个数字不能抽取,每一次抽取一个数字得到的价值为这个数字和相邻两个数字的乘积,问把整个序列最后只剩下第一个和最后一个数字时的最小价值。

思路:区间DP经典题,我们令dp[i][j]为第i到第j个数字去光后的价值,转移方程dp[i][j]=min(dp[i][j],dp[i][k]+dp[k][j]+a[i]*a[j]*a[k])


#include <cstdio>#include <queue>#include <cstring>#include <iostream>#include <cstdlib>#include <algorithm>#include <vector>#include <map>#include <string>#include <set>#include <ctime>#include <cmath>#include <cctype>using namespace std;#define maxn 100000#define LL long longint cas=1,T;int dp[105][105];int a[105];int main(){int n;while (scanf("%d",&n)!=EOF){for (int i = 0;i<n;i++)scanf("%d",&a[i]);for (int i = 0;i<n-2;i++)dp[i][i+2]=a[i]*a[i+1]*a[i+2];int len;for (len=3;len<n;len++){for (int i = 0;i+len<n;i++){int j = len+i;for (int k = i+1;k<j;k++){if (dp[i][j]==0)dp[i][j]=dp[i][k]+dp[k][j]+a[i]*a[j]*a[k];dp[i][j]=min(dp[i][j],dp[i][k]+dp[k][j]+a[i]*a[k]*a[j]);}}}printf("%d\n",dp[0][n-1]);}//freopen("in","r",stdin);//scanf("%d",&T);//printf("time=%.3lf",(double)clock()/CLOCKS_PER_SEC);return 0;}

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

610 1 50 50 20 5

Sample Output

3650


0 0