CF1185C2 题解
洛谷传送门 & CF 传送门
思路
第一反应是准备一个大根堆
# include <bits/stdc++.h>
using namespace std;
int n, m, x, now, tot;
priority_queue <int> q;
int main () {
ios::sync_with_stdio (0);
cin.tie (0);
cout.tie (0);
cin >> n >> m;
while (n --) {
cin >> x;
now += x;
while (now > m && ! q.empty ())
now -= q.top (), q.pop (), ++ tot; //tot 用于记录目前删掉的数个数
q.push (x);
cout << tot << ' ';
}
return 0;
}
然后,你会发现 WA 在了第
3 10
5 6 5
我们来分析一下这个方法的漏洞。这个方法的错误原因就在于题目规定了
于是,我们要弥补这个漏洞的突破口就在于我们只需要把操作回退到加
当
代码
# include <bits/stdc++.h>
using namespace std;
int n, m, x, now, tot;
priority_queue <int> q;
priority_queue <int, vector <int>, greater <int>> poper;
int main () {
ios::sync_with_stdio (0);
cin.tie (0);
cout.tie (0);
cin >> n >> m;
while (n --) {
cin >> x;
now += x;
while (! q.empty () && now > m)
now -= q.top (), poper.push (q.top ()), q.pop (), ++ tot;
cout << tot << ' ';
if (poper.empty () || poper.top () >= x) { //不用换
q.push (x);
continue;
}
now -= x;
++ tot; //x 也是个数啊,所以要把删掉的数 +1
while (! poper.empty () && now + poper.top () <= m)
now += poper.top (), q.push (poper.top ()), poper.pop (), -- tot;
poper.push (x);
}
return 0;
}