您的位置:首页 > 产品设计 > UI/UE

Cut the Sequence (单调队列优化DP)

2018-04-06 11:53 253 查看
Given an integer sequence { an } 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.
InputThe first line of input contains two integer N (0 < N ≤ 100 000), M. The following line contains N integers describes the integer sequence. Every integer in the sequence is between 0 and 1 000 000 inclusively.
OutputOutput one integer which is the minimum sum of the maximum integer of each part. If no such cuttings exist, output −1.
Sample Input
8 17
2 2 2 8 1 8 2 1
Sample Output
12
#include <iostream>
#include <cstdio>
#include <cmath>

using namespace std;

int N;
long long M;
long long a[100005];
int que[100005];
long long sum[100005];
long long dp[100005];

int main()
{
cin>>N>>M;
int flag=1;
for(int i=1;i<=N;i++){
cin>>a[i];
if(a[i]>M)
flag=0;
sum[i]=sum[i-1]+a[i];
}
int s=1,t=1,p=0;
if(flag==1){
for(int i=1;i<=N;i++){
while(s<t&&a[que[t-1]]<=a[i]) t--;
que[t++]=i;
while(sum[que[t-1]]-sum[p]>M){
p++;
if(que[s]<=p){
s++;
}
}
dp[i]=dp[p]+a[que[s]];
for(int j=s;j<t;j++){
dp[i]=min(dp[i],dp[que[j]]+a[que[j+1]]);
}
}
}
if(flag==0){
cout<<-1;
}
else{
cout<<dp
;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: