当前位置:网站首页>区间DP-链式石子合并
区间DP-链式石子合并
2022-07-23 20:01:00 【Duktig_7】
问题描述
N堆排成一排的石子,编号为1,2,…,n。每堆石子都有一堆重量,现将所有石子合并为一堆。两堆石子合并为一堆所花费代价为两堆石子的重量和,合并为的一堆的石子的重量为两堆石子重量之和。试求将所有石子合并为一堆所花费的最小代价。
输入格式
第一行输入一个数N,表示石子的堆数;第二行输入N个整数,分别表示N堆石子的重量。
输出格式
输出将N堆石子合并为一堆的最小花费代价
数据范围
1<=N<=30
输入样例
4
1 3 5 2
输出样例
22
解题思路
将N堆石子合并为一堆的过程,每一步均为两堆石子合并为一堆,石子堆数减少一;每次合并的两堆石子,可能是由最初N堆石子中的几堆组成的。
- 记 [l,r] 为由(l,l+1,l+2,…,r)合并为一堆的石子;每一堆石子都是由两堆石子合并得到的,则 [l,r] 石子可能是由 [l,k] 和 [k+1,r](l<=k<r)两堆石子合并得到的。
- 记 f[l,r] 为得到 [l,r] 这一堆石子付出的最小代价;若石子 [l,r] 由 [l,k] 和 [k+1,r] 两堆合并得到,则 得到[l,r]这堆石子付出的代价 为 得到[l,k]这堆石子付出的代价 和 得到[k+1,r]这堆石子 和 将[l,k]和[k+1,r]两堆石子合并为一堆付出的代价 ,由此得到递推公式:
f[l,r]=min(f[l,k]+f[k+1,r]+s[r]-s[l-1]),(l<r)
f[l,r]=0,(l == r)
其中,s[i]为前i堆石子重量的前缀和,(l <= k < r)
- 初值:任意i∈[1,N],f[l][l]=0,其余为正无穷
- 目标:f[1][n]
实现代码
#include<iostream>
#include<algorithm>
using namespace std;
const int N=310;
int n;
int w[N],f[N][N];
int s[N];
int main()
{
cin>>n;
for(int i=1;i<=n;i++) cin>>w[i];
//求前缀和
for(int i=1;i<=n;i++) s[i]=s[i-1]+w[i];
for(int len=2;len<=n;len++)
for(int i=1;i+len-1 <= n;i++){
int l=i,r=i+len-1;
f[l][r]=1e8;//找不同k条件下f[l][r]的最小值,所以不希望他的初始值有影响,所以设为正无穷
for(int k=i;k<r;k++)//枚举[l,r-1]范围内的不同区间
f[l][r]=min(f[l][r],f[l][k]+f[k+1][r]+s[r]-s[l-1]);
}
//输出结果即区间[1,n]的值
cout<<f[1][n]<<endl;
return 0;
}
边栏推荐
猜你喜欢

多子系统多业务模块的复杂数据处理——基于指令集物联网操作系统的项目开发实践

剑指 Offer II 115. 重建序列

AtCoder——Subtree K-th Max

Leetcode 151. invert words in strings

D2Admin框架基本使用

How to solve the problem that the solid state disk cannot be found when installing win11?

Task03 notes 2

Edge cloud | 1. overview

I deliberately leave a loophole in the code. Is it illegal?

The numerical sequence caused by the PostgreSQL sequence cache parameter is discontinuous with interval gap
随机推荐
今日睡眠质量记录81分
21. Mix in details
平安证券低佣金开户链接安全吗,怎么办理低佣金
Prepare for pressure test with JMeter and visualvw
Chinese [easy to understand] cannot be set when installing SVN localization package
JDK installation package and MySQL installation package sorting
Reduced order method of linear algebraic determinant calculation method
21.mixin混入详解
osgearth使用sundog公司的triton海洋和silverlining云彩效果
2022山东养老展,中国国际养老服务业展览会,济南老龄产业展
微软网站上关于在Edge浏览器中打开或关闭smartScreen的说明有误
Data warehouse 4.0 notes - data warehouse environment construction - DataGrid preparation and data preparation
How to reset the computer system? The method is actually very simple
2022DASCTF MAY
Detailed writing process of impala
next数值型数据类型()出现输入错误后,下次依然能正常输入
What antenna is used for ant interface_ There is an interface at the back of the TV that says standard ant 75 Euro input. What does it mean, antenna? Can you connect the closed route "Suggested collec
Parity rearrangement of Bm14 linked list
使用TinkerPop框架对GDB增删改查
去广场吃饭