其他分享
首页 > 其他分享> > 动态规划Cut the Sequence 题解

动态规划Cut the Sequence 题解

作者:互联网

题目描述

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