石子归并 51Nod - 1021(区间DP入门题)

N堆石子摆成一条线。现要将石子有次序地合并成一堆。规定每次只能选相邻的2堆石子合并成新的一堆,并将新的一堆石子数记为该次合并的代价。计算将N堆石子合并成一堆的最小代价。

例如: 1 2 3 4,有不少合并方法

1 2 3 4 => 3 3 4(3) => 6 4(9) => 10(19)

1 2 3 4 => 1 5 4(5) => 1 9(14) => 10(24)

1 2 3 4 => 1 2 7(7) => 3 7(10) => 10(20)

括号里面为总代价可以看出,第一种方法的代价最低,现在给出n堆石子的数量,计算最小合并代价。

AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
//#define int long long
using namespace std;
const int maxn=1e6+5;
int dp[1005][1005],sum[maxn],a[maxn];
int main(){
	memset(dp,0x3f3f3f3f,sizeof(dp));
	int n;
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>a[i];
		sum[i]=sum[i-1]+a[i];
		dp[i][i]=0;
	}
	for(int len=2;len<=n;len++){
		for(int i=1;i+len-1<=n;i++){
			int l=i,r=i+len-1;
			for(int k=l;k<=r;k++){
				dp[l][r]=min(dp[l][k]+dp[k+1][r]+sum[r]-sum[l-1],dp[l][r]);
			}
		}
	}
	cout<<dp[1][n]<<endl;
}
 

猜你喜欢

转载自blog.csdn.net/Alanrookie/article/details/107560228
今日推荐