51node 1021 石子归井(dp)

https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1021&judgeId=593366

1021 石子归并

基准时间限制:1 秒 空间限制:131072 KB 分值: 20 难度:3级算法题

收藏

关注

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)

扫描二维码关注公众号,回复: 2554604 查看本文章

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

Input

第1行:N(2 <= N <= 100)
第2 - N + 1:N堆石子的数量(1 <= A[i] <= 10000)

Output

输出最小合并代价

Input示例

4
1
2
3
4

Output示例

19

dp

#include<iostream>
#include<string.h>
#include<algorithm>
#include<queue>
#include<vector>
#define inf 0x3f3f3f3f
#define ll long long
#define maxn 1005
using namespace std;
ll a[maxn];
ll sum[maxn];
ll dp[maxn][maxn];
int main()
{
	int t;
	cin>>t;
	memset(sum,0,sizeof(sum));
	for(int i=1;i<=t;i++)
	{
		cin>>a[i];
		sum[i]=sum[i-1]+a[i];
	}
	memset(dp,0,sizeof(dp));
		for(int len=2;len<=t;len++)//长度
		{
			for(int i=1;i<=t-len+1;i++)//开始位置
			{
				int end=i+len-1;//结束位置
				 dp[i][end] = inf;
				for(int j=i;j<end;j++)//之间的搜索
				{
					dp[i][end]=min(dp[i][end],dp[i][j]+dp[j+1][end]+sum[end]-sum[i-1]);
				}
			}
		}
		cout<<dp[1][t]<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41453511/article/details/81411452