-
Notifications
You must be signed in to change notification settings - Fork 174
/
Copy pathSliding Cost.cpp
84 lines (73 loc) · 1.58 KB
/
Sliding Cost.cpp
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxN = 2e5+1;
int N, K, x[maxN];
ll losum, hisum;
multiset<int> lo, hi;
ll cost(){
ll median = *lo.rbegin();
ll locost = (median * lo.size()) - losum;
ll hicost = hisum - (median * hi.size());
return locost + hicost;
}
void lowToHigh(){
ll val = *lo.rbegin();
lo.erase(lo.lower_bound(val));
hi.insert(val);
losum -= val;
hisum += val;
}
void highToLow(){
ll val = *hi.begin();
lo.insert(val);
hi.erase(hi.lower_bound(val));
losum += val;
hisum -= val;
}
void adjust(){
int tot = (int) (lo.size() + hi.size());
if(lo.size() < (tot+1)/2) highToLow();
else if(lo.size() > (tot+1)/2) lowToHigh();
}
void erase(ll val){
ll median = *lo.rbegin();
if(val > median){
hi.erase(hi.lower_bound(val));
hisum -= val;
} else {
lo.erase(lo.lower_bound(val));
losum -= val;
}
adjust();
}
void insert(ll val){
if(lo.size() == 0){
lo.insert(val);
losum += val;
return;
}
ll median = *lo.rbegin();
if(val > median){
hi.insert(val);
hisum += val;
} else {
lo.insert(val);
losum += val;
}
adjust();
}
int main(){
scanf("%d %d", &N, &K);
for(int i = 0; i < K; i++){
scanf("%d", &x[i]);
insert(x[i]);
}
printf("%lld%c", cost(), (" \n")[K==N]);
for(int i = K; i < N; i++){
scanf("%d", &x[i]);
insert(x[i]);
erase(x[i-K]);
printf("%lld%c", cost(), (" \n")[i==N-1]);
}
}