Multiplication Puzzle POJ–1651 区间dp
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, scoring10*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 6
10 1 50 50 20 5
Sample Output 3650
一道初级的区间dp,重点在于给定区间,抽走一张牌,其对应的值为左边区间的最小值加右边区间的最小值加上抽出这张卡本身的代价。
拿例子来说,我们假定它不断的抽卡,抽到中间只有最后一张了,这是必然会发生的,那在这样的情况下哪一张才是最后一张?这就是要通过dp去遍历找出其最小值的情况。
我们先验1,那么就是10*1*50+10到1之间的最小值——就是0+从1-5之间的最小值,然后从1-5之间的最小值就成了一个子问题,
如此循环,如果遇到不足三个数的情况,那就为0,如果刚好三个数,那么就只有抽掉中间那张卡,不然就遍历一边看看除那张卡花费代价最小。
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
#include<string>
#include<queue>
#include<climits>
#include<map>
#include<stack>
#include<list>
#include<set>
#include<ctime>
#include<cstdlib>
#include<sstream>
#define file_in freopen("input.txt","r",stdin)
#define MAX 100005
#define INF 0x3f3f3f3f
#define HASH 100019
#define MAX_C 100
#define MAP_IT(type1,type2) map<type1,type2>::iterator
using namespace std;
#define ll long long
#define FF(x,y,i) for(int i=x;i<y;i++)
int dp[105][105];
vector<int>sto;
int solve(int lef, int rig) {
if (dp[lef][rig] != INF)
return dp[lef][rig];
if (lef + 1 == rig || lef == rig)
{
dp[lef][rig] = 0;
return 0;
}
for (int i = lef + 1; i < rig; i++)
{
dp[lef][rig] = min(dp[lef][rig], solve(lef, i) + solve(i, rig) + sto[lef] * sto[i] * sto[rig]);
}
return dp[lef][rig];
}
int main() {
int t;
cin >> t;
sto.resize(t);
FF(0, t, i) cin >> sto[i];
for (int i = 0; i < t; i++)
{
for (int j = 0; j < t; j++)
{
dp[i][j] = INF;
}
}
solve(0, t - 1);
cout << solve(0, t - 1);}
/*
5
5 1 2 3 4
0
6
2 1 3
5 4 6 2
0
0
*/