-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path1076.cc
81 lines (70 loc) · 1.56 KB
/
1076.cc
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
#include <bits/stdc++.h>
using namespace std;
/**
Supports - Add element / Remove element / Find Median operations.
*/
class RunningMedian {
public:
void AddElement(int v) {
items_ += 1;
auto it = right_half_.begin();
if (it == right_half_.end() || v <= *it)
left_half_.insert(v);
else
right_half_.insert(v);
ReBalance();
}
void RemoveElement(int v) {
items_ -= 1;
auto it = left_half_.find(v);
if (it != left_half_.end())
left_half_.erase(it);
else {
it = right_half_.find(v);
right_half_.erase(it);
}
ReBalance();
}
int GetMedian() {
assert(items_ > 0);
auto it = left_half_.rbegin();
return *it;
}
private:
void ReBalance() {
int reqd_left_size = (items_ + 1) / 2;
while (left_half_.size() < reqd_left_size) {
auto it = right_half_.begin();
left_half_.insert(*it);
right_half_.erase(it);
}
while (left_half_.size() > reqd_left_size) {
auto it = left_half_.end();
it--;
right_half_.insert(*it);
left_half_.erase(it);
}
}
// |left_half_| contains the ceil(|items_|/2) elements, and the rest are
// in |right_half_|.
multiset<int> left_half_, right_half_;
int items_ = 0;
};
int main() {
RunningMedian running_median;
int n, k;
cin >> n >> k;
vector<int> arr(n);
for (int &x: arr)
cin >> x;
for (int i = 0; i < k; i++)
running_median.AddElement(arr[i]);
cout << running_median.GetMedian() << " ";
for (int i = k; i < n; i++) {
running_median.RemoveElement(arr[i - k]);
running_median.AddElement(arr[i]);
cout << running_median.GetMedian() << " ";
}
cout << "\n";
return 0;
}