-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathDynamic median.cpp
70 lines (64 loc) · 1.45 KB
/
Dynamic median.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
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <numeric>
#include <algorithm>
#include <functional>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <utility>
#include <cassert>
#include <iomanip>
#include <ctime>
using namespace std;
int t;
int x;
multiset<int> small, big;
void fix(){
while((int)small.size() - 1 > (int)big.size()){
int x = *(--small.end());
big.insert(x);
small.erase(small.find(x));
}
while((int)small.size() < (int)big.size()){
int x = *(big.begin());
small.insert(x);
big.erase(big.find(x));
}
while(!small.empty() && !big.empty() && *(--small.end()) > *(big.begin())){
int x = *(--small.end());
int y = *(big.begin());
small.erase(small.find(x));
big.insert(x);
big.erase(big.find(y));
small.insert(y);
}
}
int main(int argc, const char * argv[]) {
scanf("%d", &t);
while(t --){
small.clear();
big.clear();
while(scanf("%d", &x)){
if(x == 0)
break;
if(x > 0){
small.insert(x);
fix();
}
else{
x = *(--small.end());
printf("%d\n", x);
small.erase(small.find(x));
fix();
}
}
if(t > 0)
printf("\n");
}
return 0;
}