0%

ABC281E Least Elements 题解

ABC281E Least Elements 题解

前言

去年的12月份,在**期间闲得无聊,就看了看当时的at,发现这道题比较可做,于是一直咕到了现在。

思路

对于这种连续区间问题,答案很明显,就是算变化。

先用二叉堆维护初始问题的答案,假设现在向右移动一格。

那么最左边的数不能要了,如果它本来就不在前 $k$ 小,那么不会产生影响,如果在,就删除它,加入之前不在的最小的数。

最右边会加一个数,如果它不在现在的前 $k$ 小,不用管,如果在,就删除最大的一个数。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define mp make_pair
const int N = 2e5+10;
int n,m,k,a[N],del[N],ins[N];
ll ans[N];
pair<int,int> tmp[N];
priority_queue<pair<int,int> > q1,q2;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n>>m>>k;
for (int i=1;i<=n;i++) cin>>a[i];
for (int i=1;i<=m;i++){
if (q1.size()<k) q1.push(mp(a[i],i));
else if (a[i]<q1.top().first){
q2.push(mp(-q1.top().first,q1.top().second));
q1.pop();
q1.push(mp(a[i],i));
}
else q2.push(mp(-a[i],i));
}
for (int i=1;i<=k;i++){
tmp[i] = q1.top();
ans[1]+=q1.top().first;
q1.pop();
}
cout<<ans[1]<<" ";
for (int i=1;i<=k;i++) q1.push(tmp[i]),ins[tmp[i].second] = 1;
int sz = k;
for (int i=2;i<=n-m+1;i++){
ans[i] = ans[i-1];
int pos1 = i-1,pos2 = i+m-1;
while (!q1.empty() && q1.top().second<i-1) q1.pop();
if (ins[pos1]){
ans[i]-=a[pos1];
ins[pos1] = 0;
sz--;
}
while (!q1.empty() && q1.top().second<i) q1.pop();
q2.push(mp(-a[pos2],pos2));
while (!q2.empty() && q2.top().second<i) q2.pop();
if (sz<k){
q1.push(mp(-q2.top().first,q2.top().second));
ans[i]+=a[q2.top().second];
ins[q2.top().second] = 1;
q2.pop();
sz++;
}
else if (-q2.top().first<q1.top().first){
ans[i]-=q1.top().first;
ins[q1.top().second] = 0;
int tmp1 = -q1.top().first,tmp2 = q1.top().second;
q1.pop();
q1.push(mp(-q2.top().first,q2.top().second));
q2.push(mp(tmp1,tmp2));
ins[q2.top().second] = 1;
ans[i]+=a[q2.top().second];
q2.pop();
}
cout<<ans[i]<<" ";
}
return 0;
}