Multiplication Puzzle
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 11740 | Accepted: 7275 |
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.
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
If he would take the cards in the opposite order, i.e. 50, then 20, then 1, the score would be
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
题意:每次取出来一个数,并将其与左右值相乘加到最后结果中,直到取完为止.不可取两端的值.
思路:区间dp,先预处理任意相邻3个之积,然后从长度为4的区间开始枚举,dp[i][j] = min(dp[i][j],dp[i][x]+dp[x][j]+a[i]*a[x]*a[j])
意思就是若区间i到j只剩下a[i],a[x],a[j]三个值时,dp[i][j]的值是多少.
代码:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<cstring>
#include<string>
#include<vector>
#include<cmath>
#include<map>
#define mem(a,b) memset(a,b,sizeof(a))
#define mod 1000000007
using namespace std;
typedef long long ll;
const int maxn = 1e6+5;
const double esp = 1e-7;
const int ff = 0x3f3f3f3f;
int n;
int a[520];
ll dp[120][120];
int main()
{
cin>>n;
for(int i = 1;i<= n;i++)
cin>>a[i];
for(int i = 1;i< n-1;i++)
dp[i][i+2] = a[i]*a[i+1]*a[i+2];
for(int k = 4;k<= n;k++)//枚举长度
{
for(int i = 1,j = i+k-1;j<= n;i++,j++)//枚举起点终点
{
for(int x = i+1;x< j;x++)//枚举中间点
{
if(dp[i][j]!= 0)
dp[i][j] = min(dp[i][j],dp[i][x]+dp[x][j]+a[i]*a[x]*a[j]);
else
dp[i][j] = dp[i][x]+dp[x][j]+a[i]*a[x]*a[j];
}
}
}
cout<<dp[1][n]<<endl;
return 0;
}