[POJ-1651]Multiplication Puzzle [區間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, 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 150
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <string>
#include <math.h>
#include <stack>
#include <vector>
#include <queue>
#include <set>
#include <map>
using namespace std;
#define rep(i, l, r) for(int i = l; i < r; i++)
#define per(i, r, l) for(int i = r; i >= l; i--)
#define dbg(...) cerr<<"["<<#__VA_ARGS__":"<<(__VA_ARGS__)<<"]"<<"\n"
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int>pii;
const int N = (int) 100 + 11;
const int M = (int) 1e6 + 11;
const int MOD = (int) 1e9 + 7;
const int INF = (int) 0x3f3f3f3f;
const ll INFF = (ll) 0x3f3f3f3f3f3f3f3f;
/*-----------------------------------------------------------*/
ll val[N], dp[N][N];
int main(){
int n; scanf("%d" ,&n);
rep(i, 0, n) scanf("%lld", val + i + 1);
rep(i, 2, n) dp[1][i] = val[i] * val[i - 1] * val[i + 1]; // 初始化
for(int width = 2; width <= n - 2; width++){
for(int L = 2; L + width - 1 <= n - 1; L++){
int R = L + width - 1;
dp[width][L] = INFF;
for(int mid = L; mid <= R; mid++){// mid 為列舉[L, R]中最後一個取出
dp[width][L] = min(dp[width][L], dp[mid - L][L] + dp[R - mid][mid + 1] + val[mid] * val[L - 1] * val[R + 1]);
}
}
}
cout << dp[n - 2][2] <<"\n";
return 0;
}