[NYIST737]石子合并(一)(区间dp)

题目链接:http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=737

很经典的区间dp,发现没有写过题解。最近被hihocoder上几道比赛题难住了,特此再回头重新理解一遍区间dp。

这道题的题意很明确,有一列石子堆,每堆石子都有数量,还有一个操作:相邻两堆石子合并成一堆石子,这个操作的代价是这两堆石子的数目和。要找一个合并次序,使得代价最小,最终输出最小代价。

这个题可以用动态规划,简单分析可以得知,这一列石子堆都可以划分为小区间,每个小区间需要解决的问题和大问题是一样的。

假如有2堆石子a1 a2,那合并操作只有1种,就是直接合并这两堆石子,代价是a1+a2。

假如有3堆石子a1 a2 a3,那合并操作只有2种,先合并前两堆或先合并后两堆,代价分别是(a1+a2)+(a1+a2)+a3和(a2+a3)+a1+(a2+a3)。

……

我们发现他们在自己小区间内解决问题的时候,对于他们内部的合并顺序谁先谁后是不影响全局的,而且仔细分析可以知道已经得到的子问题的最优解也一定包含于原问题的最优解之内。

比如还是刚才的例子,有三堆石子分别是1 2 3

每次2堆考虑的时候,有两种情况,合并1 2或2 3,代价分别是1+2和2+3。

再合并,考虑3堆的时候,那就是前面2堆的情况扩展一堆的情况了,这个扩展可以是(1+2)+3,也可以是(2+3)+1。加上之前的代价,他们的总和分别是9和11。

 /*
━━━━━┒ギリギリ♂ eye!
┓┏┓┏┓┃キリキリ♂ mind!
┛┗┛┗┛┃\○/
┓┏┓┏┓┃ /
┛┗┛┗┛┃ノ)
┓┏┓┏┓┃
┛┗┛┗┛┃
┓┏┓┏┓┃
┛┗┛┗┛┃
┓┏┓┏┓┃
┛┗┛┗┛┃
┓┏┓┏┓┃
┃┃┃┃┃┃
┻┻┻┻┻┻
*/
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <climits>
#include <complex>
#include <fstream>
#include <cassert>
#include <cstdio>
#include <bitset>
#include <vector>
#include <deque>
#include <queue>
#include <stack>
#include <ctime>
#include <set>
#include <map>
#include <cmath>
using namespace std;
#define fr first
#define sc second
#define cl clear
#define BUG puts("here!!!")
#define W(a) while(a--)
#define pb(a) push_back(a)
#define Rint(a) scanf("%d", &a)
#define Rll(a) scanf("%I64d", &a)
#define Rs(a) scanf("%s", a)
#define Cin(a) cin >> a
#define FRead() freopen("in", "r", stdin)
#define FWrite() freopen("out", "w", stdout)
#define Rep(i, len) for(LL i = 0; i < (len); i++)
#define For(i, a, len) for(LL i = (a); i < (len); i++)
#define Cls(a) memset((a), 0, sizeof(a))
#define Clr(a, x) memset((a), (x), sizeof(a))
#define Fuint(a) memset((a), 0x7f7f, sizeof(a))
#define lrt rt << 1
#define rrt rt << 1 | 1
#define pi 3.14159265359
#define RT return
#define lowbit(x) x & (-x)
#define onenum(x) __builtin_popcount(x)
typedef long long LL;
typedef long double LD;
typedef unsigned long long Uint;
typedef pair<LL, LL> pii;
typedef pair<string, LL> psi;
typedef map<string, LL> msi;
typedef vector<LL> vi;
typedef vector<LL> vl;
typedef vector<vl> vvl;
typedef vector<bool> vb; const int maxn = ;
int dp[maxn][maxn];
int a[maxn];
int n; int main() {
FRead();
while(~Rint(n)) {
For(i, , n+) Rint(a[i]);
For(i, , n+) a[i] += a[i-];
Cls(dp);
for(int h = ; h <= n; h++) {
for(int i = ; i <= n - h + ; i++) {
int j = i + h - ;
dp[i][j] = 0x7f7f7f;
for(int k = i; k <= j; k++) {
dp[i][j] = min(dp[i][j], dp[i][k]+dp[k+][j]+a[j]-a[i-]);
}
}
}
printf("%d\n", dp[][n]);
}
RT ;
}
上一篇:SQL注入--宽字节注入


下一篇:Javascript - 栈 和 单链表