当前位置:网站首页>(动态规划例题)石子合并
(动态规划例题)石子合并
2022-07-22 23:51:00 【咸蛋_dd】
解题思路非常棒,建议没事就嚼一嚼。
设有 NN 堆石子排成一排,其编号为 1,2,3,…,N1,2,3,…,N。
每堆石子有一定的质量,可以用一个整数来描述,现在要将这 NN 堆石子合并成为一堆。
每次只能合并相邻的两堆,合并的代价为这两堆石子的质量之和,合并后与这两堆石子相邻的石子将和新堆相邻,合并时由于选择的顺序不同,合并的总代价也不相同。
例如有 44 堆石子分别为 1 3 5 2, 我们可以先合并 1、21、2 堆,代价为 44,得到 4 5 2, 又合并 1,21,2 堆,代价为 99,得到 9 2 ,再合并得到 1111,总代价为 4+9+11=244+9+11=24;
如果第二步是先合并 2,32,3 堆,则代价为 77,得到 4 7,最后一次合并代价为 1111,总代价为 4+7+11=224+7+11=22。
问题是:找出一种合理的方法,使总的代价最小,输出最小代价。
输入格式
第一行一个数 NN 表示石子的堆数 NN。
第二行 NN 个数,表示每堆石子的质量(均不超过 10001000)。
输出格式
输出一个整数,表示最小代价。
数据范围
1≤N≤3001≤N≤300
输入样例:
4
1 3 5 2
输出样例:
22#include <bits/stdc++.h>
using namespace std;
const int N=310;
int n;
int s[N];
int f[N][N];
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%d",&s[i]);
for(int i=1;i<=n;i++) s[i]=s[i-1]+s[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;
for(int k=l;k<=r-1;k++)
f[l][r]=min(f[l][r],f[l][k]+f[k+1][r]+s[r]-s[l-1]);
}
}
printf("%d\n",f[1][n]);
}
边栏推荐
- Redistemplate pipeline use
- 我用Flutter开发了一个类似微信可运行小程序的App
- 如何防范各类联属欺诈?
- 用Flutter开发了一个可运行小程序的App
- [GNN report] Li Jia, Hong Kong University of science and technology: Rethinking graph anomaly detection - what kind of graph neural network do we need?
- Arcgis js api二次开发——加载国家天地图
- PKS Secretary & brother | review the past and know the new
- pinia的基本使用
- Bufferedinputstream buffer fill problem
- 常用cmd命令 总结 二进制与十进制的转换
猜你喜欢

1.5万字概括ES6全部特性

医院PACS源码 PACS超声科室源码 DICOM影像工作站源码【源码免费分享】

MySQL 分库分表及其平滑扩容方案

On the stability of common sorting

Algorithm --- 2D array mesh migration (kotlin)

wireshark抓包工具基本使用

【MySQL学习】多个不同版本MySQL安装、MySQL8和MySQL5.7同时安装与使用,压缩版

数据分析与隐私安全成 Web3.0 成败关键因素,企业如何布局?

outlook客户端 outlook.com邮箱设置方法

面试官:生成订单30分钟未支付,则自动取消,该怎么实现?
随机推荐
图的存储 ~
小迪和小辉
浅谈——网络安全架构设计(三)
我用Flutter开发了一个类似微信可运行小程序的App
Swift - 标红的修饰词
[GNN report] Li Jia, Hong Kong University of science and technology: Rethinking graph anomaly detection - what kind of graph neural network do we need?
svn: E000022: Can‘t convert string from ‘UTF-8‘ to native encoding 问题解决
Cases on classes and objects
[GNN report] Huawei Noah lab Zhou Min: graph data modeling and analysis from the perspective of curvature
常用cmd命令 总结 二进制与十进制的转换
从一个 bug 中延伸出 canvas 最大内存限制和浏览器渲染原理
坚持陪同学习
SSH password free login configuration
物联网安装调试员丨让“智慧”生活早日来临
bs4根据属性索引与名称索引对象
odbc excel--2022-07-21
二叉树的结点定义 、遍历 ~
用户登录程序C语言实现
最少交换次数
Dark horse programmer - interface testing - four-day learning interface testing - the second day - Interface use case design, test points, function testing, security testing, performance testing, sing