forked from Diusrex/UVA-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path10107 What is the Median.cpp
48 lines (38 loc) · 1.2 KB
/
10107 What is the 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
#include <iostream>
#include <queue>
using namespace std;
int main()
{
priority_queue<int> belowMedian;
priority_queue<int, std::vector<int>, std::greater<int> > aboveMedian;
int current;
cin >> current;
// special case, when it did not have any elements
belowMedian.push(current);
cout << current << '\n';
int previousMedian = current;
while (cin >> current)
{
if (current <= previousMedian)
belowMedian.push(current);
else
aboveMedian.push(current);
if (belowMedian.size() > aboveMedian.size() + 1)
{
int swapped = belowMedian.top();
belowMedian.pop();
aboveMedian.push(swapped);
}
else if (belowMedian.size() < aboveMedian.size())
{
int swapped = aboveMedian.top();
aboveMedian.pop();
belowMedian.push(swapped);
}
if (belowMedian.size() == aboveMedian.size())
previousMedian = belowMedian.top() + (aboveMedian.top() - belowMedian.top()) / 2;
else
previousMedian = belowMedian.top();
cout << previousMedian << '\n';
}
}