Created
September 2, 2020 02:02
-
-
Save sergiosvieira/fd09196d94b38d350473d4b897315d1d to your computer and use it in GitHub Desktop.
minHeap and maxHeap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <queue> | |
| #include <iomanip> | |
| using std::cin, std::cout; | |
| using Left = std::priority_queue<double>; | |
| using Right = std::priority_queue<double, std::vector<double>, std::greater<double>>; | |
| int main() { | |
| double value = 0; | |
| Left l;// MaxHeap | |
| Right r;// MinHeap | |
| int size; | |
| cin >> size; | |
| while (cin >> value) { | |
| // first insert | |
| if (l.empty()) { | |
| l.push(value); | |
| } else if (value > l.top()) { | |
| r.push(value); | |
| } else l.push(value); | |
| // move top value from left to right | |
| // or from right to left | |
| if (l.size() > r.size() + 1) { | |
| r.push(l.top()); | |
| l.pop(); | |
| } else if (r.size() > l.size()) { | |
| l.push(r.top()); | |
| r.pop(); | |
| } | |
| // median | |
| if (l.size() > r.size()) { | |
| cout << std::fixed | |
| << std::setprecision(1) | |
| << l.top() | |
| << '\n'; | |
| } else cout << std::fixed | |
| << std::setprecision(1) | |
| << (l.top() + r.top()) / 2. | |
| << '\n'; | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment