简化题意
-
给定一个长度为 的序列 ,通过一个容量为 的栈进行中转,希望将序列变成一个非递减排列。
-
对于每个数可以进行入栈、出栈,或直接进入到结果序列。
-
对于每一个序列中的数字 ,你可以消耗总和不超过 的成本,将它们变成任意正整数。
-
求满足要求的最小栈容量 。
思路
首先,栈的容量 具有明显的单调性:如果容量为 时能完成排序,那么容量大于 时也一定能完成。因此,我们可以通过二分答案将原问题转化为:给定容量 ,在满足条件的前提下,是否能实现非递减序列。
然后,由于每次只有长度为 的栈,所以我们每次只能处理长度为 的区间。
其次,因为最终形成的序列需满足非递减排列,这意味着:离开系统的数必须是当前全局最大的数。所以,每次操作就是判断在当前的区间内,我们是否能够找到全局最大值。注意:
- 当我们在当前的区间内找不到当前的最大值时,如果有初始为 的空矿车,为了消耗最少的 ,我们贪心地将这个 变为当前全局最大的宝石数,并让其离开。
由于我们现在的问题就是:如何快速找出当前区间里面的最大值是不是全局最大值。想一想,发现优先队列可以很好地完成这个问题:
- 维护一个大根堆
p存入所有初始宝石数,代表我们“期望”依次排出的最大值。 - 再维护另一个大根堆
q存入当前处理区间内的宝石最大值。 - 对于 ,我们可以通过一个变量来维护当前区间中 的个数,每次查询的时候只需要判断 的消耗有没有超出即可。
代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<queue>
#include<vector>
#include<stack>
#include<cmath>
#include<ctime>
#include<set>
#include<map>
#include<bitset>
#include<iomanip>
#include<unordered_map>
#include<unordered_set>
#define db double
#define ll long long
#define int ll
#define endl "\n"
#define fi first
#define se second
#define pii pair<int,int>
#define lowbit(x) x&(-x)
#define INF 0x3f3f3f3f3f3f3f3f
#define BUG cout<<"I love You"<<endl;
using namespace std;
const int N = 3e5 + 10;
inline int read()
{
int x = 0, f = 1;
char ch = getchar();
while(ch < '0' || ch > '9')
{
if(ch == '-')
f = -1;
ch = getchar();
}
while(ch >= '0' && ch <= '9')
x = x*10+ch-'0',ch = getchar();
return x * f;
}
int n,k,a[N];
bool check(int d)
{
priority_queue<int> p,q;
for(int i = 1;i<=n;++i)
p.push(a[i]);
int len = 0,cnt = 0,kk = 0;
for(int i = n;i>=1;--i)
{
if(a[i] != 0) q.push(a[i]);
else cnt++;
if(len == d)
{
if(!q.empty() && q.top() == p.top())
{
q.pop();
p.pop();
}
else
{
if(cnt == 0) return 0;
else
{
kk+=p.top();
cnt--;
if(kk > k)
return 0;
}
}
len--;
}
len++;
}
return 1;
}
signed main()
{
n = read(),k = read();
for(int i = 1;i<=n;++i)
a[i] = read();
int l = 0,r = n;
int ans = n;
while(l<=r)
{
int mid = (l+r)>>1;
if(check(mid))
{
ans = mid;
r = mid-1;
}
else
l = mid+1;
}
cout<<ans<<endl;
return 0;
}