ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

动态规划Cut the Sequence 题解

2022-06-11 13:02:20  阅读:158  来源: 互联网

标签:Cut sequence int 题解 sum Sequence part integer dp


题目描述

Given an integer sequence \(a_n\) of length \(N\), you are to cut the sequence into several parts every one of which is a consecutive subsequence of the original sequence. Every part must satisfy that the sum of the integers in the part is not greater than a given integer \(M\) . You are to find a cutting that minimizes the sum of the maximum integer of each part.

题意: 将一个由 \(N\) 个数组成的序列划分成若干段,要求每段数字的和不超过 \(M\),求每段的最大值的和的最小的划分方法,输出这个最小的和。

输入输出

输入

The first line of input contains two integer \(N\) (\(1 \leq N \leq 100 000\)), \(M\). The following line contains \(N\) integers describes the integer sequence. Every integer in the sequence is between \(1\) and \(1000000\) inclusively.

输出

Output one integer which is the minimum sum of the maximum integer of each part. If no such cuttings exist, output \(−1.\)

样例输入

8 17
2 2 2 8 1 8 2 1

样例输出

12

线段树维护会爆炸,简单算一下复杂度可得为 \(O(n^2 \log n)\) ,不是我们想象中的美好。

\(dp[i]\) 表示前 \(i\) 个不超过 \(m\) 的数每段最大值的和的最小值。

看起来很棘手,不好表示,再观察发现针对前 \(i\) 个答案,答案并不具备后效性,翻译成人话,前 \(i\) 个的选择情况不会影响后面的答案,限制因素只与 \(m\) 有关。

考虑转移:\(dp[i]=min(dp[i],dp[i]+max\)(前面最大的数 \(j\) 且 \(i-j\) 数和小于 \(m\)) )

使用前缀和维护,解决。

Code.

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int n,m,w[N],f[N],hh,tt,sum[N];
int main()
{
	memset(f,0x3f,sizeof f);
	f[0]=0;
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++) scanf("%d",&w[i]),sum[i]=sum[i-1]+w[i];
	for(int i=1;i<=n;i++)
	{
		int maxx=w[i];
		for(int j=i-1;sum[i]-sum[j]<=m && j>=0;j--)
		{
			f[i]=min(f[i],f[j]+maxx);
			maxx=max(maxx,w[j]);
		}
	}
	printf("%d",f[n]);
	return 0;
}

标签:Cut,sequence,int,题解,sum,Sequence,part,integer,dp
来源: https://www.cnblogs.com/EastPorridge/p/16365648.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有