- paste
分堆
- 2022-9-28 14:03:20 @
#include<bits/stdc++.h>
using namespace std;
#define ioio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define endl "\n"
#define P pair
#define P1 first
#define P2 second
#define u_map unordered_map
#define p_queue priority_queue
typedef long long ll;
const double eps=1e-6;
const int INF=0x3f3f3f3f;
const int mod=1e9+7;
const int N=1e6+7;
int dx[]={0,0,1,-1},dy[]={1,-1,0,0};
/*-------------------------------------*/
ll n,m;
ll a[N],st[N][22],sum[N];
ll c[N];
ll dp[N];
int q[N<<3],t=1,w;
bool used[N];
struct node {
ll id,x,y;
friend bool operator < (node a,node b) {
return a.x + a.y > b.x + b.y;
}
};
p_queue<node> h;
int query(int l,int r){
int k=log2(r-l+1);
return max(st[l][k],st[r-(1<<k)+1][k]);
}
int main(){
ioio
cin>>n>>m;
for(int i=1;i<=n;i++){
cin>>a[i];
st[i][0]=a[i];
sum[i]=sum[i-1]+a[i];
if(a[i]>m){
cout<<-1<<endl;
return 0;
}
}
c[0]=1;
for(int i=1;i<=n;i++)
for(int j=c[i-1];j<=n;j++)
if(sum[i]-sum[j-1]<=m){
c[i]=j;
break;
}
for(int j=1;j<=21;j++)
for(int i=1;i+(1<<j)-1<=n;i++)
st[i][j]=max(st[i][j-1],st[i+(1<<(j-1))][j-1]);
for (int i=1; i<=n; i++) {
dp[i]=INF;
dp[i] = min(dp[i],dp[c[i] - 1] + query(c[i],i));
while (t <= w && sum[i] - sum[q[t]] > m) {
used[q[t]] = 1;
t++;
}
while (t <= w && a[q[w]] < a[i]) {
used[q[w]] = 1;
w--;
}
q[++w] = i;
if (t < w)
h.push({q[w - 1],dp[q[w - 1]],a[i]});
while (!h.empty() && (used[h.top().id] || h.top().y < query(h.top().id + 1,i)))
h.pop();
if (!h.empty())
dp[i] = min(dp[i],h.top().x + h.top().y);
}
cout<<dp[n]<<endl;
return 0;
}
0 comments
No comments so far...