题目
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
10150 + 50205 + 10505 = 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
15020 + 1205 + 1015 = 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
题意
取出一个数字,但不可取第一个与最后一个,每次取出一个数字,答案加上它乘上它相邻左右的两个数,问答案的最小值。
解释
dp[i][j]代表的是取出这个区间所有的数对应区间的答案的最小值,
设k是区间上最后一个被取出的数
dp[i][j] = min(dp[i][j], dp[i][k-1]+dp[k+1][j] + a[i-1] *a[k] *a[j+1]);
首先初始化区间长度为1或者2的dp值
然后当区间间距小于2时考虑要详细,
若为0,dp[i][j] = 0+ 0 +a[i-1] *a[k] *a[j+1]
若为1,dp[i][j] = 0 + dp[j][j] +a[i-1] *a[k] *a[j+1];
当k取i到j(i,j可以取到)dp初值赋值为0,可以符合情况。
当计算dp[i][j]时对应的赋值为inf,更新得到值,不影响。
最后答案为dp[2][n-1],取完区间2到n-1答案就是我们要求的结果
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iostream>
#define maxn 102
int const inf = 0x3f3f3f3f;
using namespace std;
long long dp[maxn][maxn];
int a[maxn];
int main(){
int n;
int i, j, k;
scanf("%d", &n);
for(i = 1; i <= n; i++){
scanf("%d", &a[i]);
}
memset(dp, inf, sizeof(dp));
for(int i = 2; i <= n-1; i++){
dp[i][i] = a[i-1]*a[i]*a[i+1];
}
for(int i = 2; i <= n-2; i++){
dp[i][i+1] = min(dp[i][i]+a[i-1]*a[i+1]*a[i+2],dp[i+1][i+1]+a[i-1]*a[i]*a[i+2]);
}
//cout<<dp[3][4]<<endl;
for(i = n-3; i >= 2; i--){
for(j = i+2; j <= n-1; j++){
for(k = i+1; k <= j-1; k++)
dp[i][j] = min(dp[i][j], dp[i][k-1]+dp[k+1][j] + a[i-1]*a[k]*a[j+1]);
dp[i][j] = min(dp[i][j], 0+dp[i+1][j] + a[i-1]*a[i]*a[j+1]);
dp[i][j] = min(dp[i][j], dp[i][j-1]+ a[i-1]*a[j]*a[j+1]);
//cout<<i<<" "<<j<<" " <<dp[i][j]<<endl;
}
}
printf("%lld\n", dp[2][n-1]);
return 0;
}