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了,这个题和矩阵最优链乘有点相似。首先倒着分析,最后一次操作时肯定只有三个数,即左右两个固定的数和上一次操作剩下的一个数。至于这个数选哪个,就要枚举left+1~right-1,这就是进行决策的过程,选完数后考虑应该从怎么转移过来,大脑里模拟一下过程,就能推出转移方程dp[l][r]=min(dp[l][r],process(l,i)+process(i,r)+a[i]*a[l]*a[r]);递归地求解,边界就是长度为2的话值为0,长度为3的话值为a[l]*a[l+1]*a[r],用DP数组存储。最后求的就是dp[1][n]。
#include <iostream> #include <cstdio> #include <cstring> using namespace std; int n,a[105],dp[105][105];//最后剩下的一定是左右两端的 int process(int l,int r) { if(l+1==r) { dp[l][r]=0; return 0; } if(l+2==r) { dp[l][r]=a[l]*a[l+1]*a[r]; return dp[l][r]; } int i; if(dp[l][r]!=0x3f3f3f3f)return dp[l][r]; for(i=l+1;i<=r-1;i++) { dp[l][r]=min(dp[l][r],process(l,i)+process(i,r)+a[i]*a[l]*a[r]); } return dp[l][r]; } int main() { cin>>n; int i; memset(dp,0x3f3f3f3f,sizeof(dp)); for(i=1;i<=n;i++)scanf("%d",&a[i]); cout<<process(1,n); return 0; }