Multiplication 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
If he would take the cards in the opposite order, i.e. 50, then 20, then 1, the score would be
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 5Sample Output
3650题意:
给你一串数字,两头的数字不能动,每次划掉一个数字,并将这个数字与其左右两个数字的乘积累加到总价值内,问所有的数字被划掉后(不包括头和尾),总价值的最小值是多少。
思路:不断的计算每个子区间的最小值,最后推广到整个区间。
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<cstring>
int a[105];
int dp[105][105];
int main()
{
int i,j,k,l,t,n;
while(scanf("%d",&n)!=EOF)
{
memset(dp,0,sizeof(dp));
for(i=1;i<=n;i++)
scanf("%d",a+i);
for(l=2;l<n;l++) //l表示子区间的长度
{
for(i=1;i+l<=n;i++) //i表示起点的那个数
{
j=i+l; //j表示结束的那个数
for(k=i+1;k<j;k++) //枚举i,j之间所有的数
{
t=dp[i][k]+dp[k][j]+a[i]*a[j]*a[k];
if(!dp[i][j] || dp[i][j]>t)
{
dp[i][j]=t;
}//相当于dp[i][j] =min(dp[i][j], dp[i][k] + dp[k][j] + a[i] * a[j] * a[k])
}
}
}
printf("%d\n",dp[1][n]);
}
return 0;
}