299. 裁剪序列 - AcWing题库
#include <bits/stdc++.h>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <set>
#define x first
#define y second
#define ios ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
typedef pair<char,int> PCI;
typedef pair<LL,LL> PLL;
//typedef __int128 i128;
typedef unsigned long long ULL;
const int N=2e5+10,INF = 1e9 ,mod = 9901;
const double eps = 1e-7;
int n,a[N],q[N];
LL m ,f[N];
// f[i] 前i个分好组后的 最优价值之和
multiset<LL> s;
void remove(LL x)
{
auto it = s.find(x);
s.erase(it);
}
// [q[hh],q[tt]] 包含在[j,i]中
void solve()
{
cin >> n >> m;
for(int i=1;i<=n ;i++ )
{
cin >> a[i];
if(a[i ] > m)
{
puts("-1");return;
}
}
int hh=0,tt=0;
LL sum= 0;
// [j,i] 当前考虑的大区间
for(int i=1,j=0;i<= n;i ++ )
{
sum += a[i];
while(sum > m ) sum -= a[ ++ j ];// 用于判断 单调队列中队头是否要移动
while(hh <= tt && q[hh ] < j )
{
if(hh < tt ) remove(f[q[hh]] + a[q[hh + 1]]);
hh ++ ;
}
// q[hh] >= j
int t = tt;// 记录 队尾的 原位置
// 队尾放入较大的 数 ,在一段中 只计算最大的值
while(hh <=tt && a[q[tt ]] <= a[i])
{
if(tt != t ) remove(f[q[tt]] + a[q[tt + 1 ]]) ;
// 不是第一次删除 的时候
tt -- ;
}
// 此时 a[q[tt]] > a[i]
if(hh <= tt && tt != t ) remove(f[q[tt]] + a[q[tt+1] ]);
q[ ++ tt ] = i;
if(hh < tt ) s.insert(f[q[tt- 1]] + a[q[tt]]);
f[i] = f[j] + a[q[hh]]; // q[hh] >= j
if(s.size()) f[i] = min(f[i],*s.begin());
// *s.begin() s中最小的数
}
cout << f[n] << endl;
}
int main()
{
// freopen("1.txt","r",stdin);
ios
LL T=1;
// cin>>T;
while(T -- )
{
solve();
}
return 0;
}