Multiplication Puzzle(POJ - 1651)(动态规划-区间dp)
judge:POJ 1651
Time Limit: 1000MS
Memory Limit: 65536K
source:Northeastern Europe 2001, Far-Eastern Subregion
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
POJ 1651
Input
Output
Sample Input
6
10 1 50 50 20 5
Sample Output
3650
题意
一堆卡片,每张卡片有自己的权值,当你抽出一张卡片时你的总花费会加上这张卡片的值与旁边两张卡片的值的乘积(即选择 a i a_i ai时花费会加上 a i ∗ a i − 1 ∗ a i + 1 a_i*a_{i-1}*a_{i+1} ai∗ai−1∗ai+1,然后 a i a_i ai就消失了)。问你如何选择能使总花费最少。
不加任何优化的区间dp
代码
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#define _for(i, a) for(int i = 0; i < (a); i++)
#define _rep(i, a, b) for(int i = (a); i <= (b); i++)
typedef long long ll;
const int maxn = 105;
const int inf = 0x3f3f3f3f;
using namespace std;
int dp[maxn][maxn];
int a[maxn];
int f[maxn];
int n;
int main() {
//freopen("in.txt", "r", stdin);
while (cin >> n) {
memset(dp, 0x3f, sizeof(dp));
_for(i, n) cin >> a[i];
_rep(i, 1, n - 2) {
dp[i][i] = a[i - 1] * a[i] * a[i + 1];
}
_rep(d, 2, n - 2) {
for (int i = 1, j = i + d - 1; j < n - 1; i++, j++) {
dp[i][j] = min(dp[i][j - 1] + a[i - 1] * a[j] * a[j + 1], dp[i + 1][j] + a[i - 1] * a[i] * a[j + 1]);
_rep(k, i + 1, j - 1) {
dp[i][j] = min(dp[i][j],
dp[i][k - 1] + a[i - 1] * a[k] * a[j + 1] + dp[k + 1][j]);
}
}
}
printf("%d\n", dp[1][n - 2]);
}
return 0;
}