Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- int n;
- vector<int> heap;
- void print_heap(){
- for(auto i: heap){
- cout << i << " ";
- }
- cout << '\n';
- }
- int getParent(int val){
- if(val%2 == 0){
- return (val-2)/2;
- }else{
- return (val-1)/2;
- }
- }
- void up_heap(int idx){
- if(idx == 0) return;
- int parent = getParent(idx);
- if(heap[parent]>heap[idx]){
- swap(heap[parent], heap[idx]);
- //cout << "swap: " << heap[parent] << ", " << heap[idx] << '\n';
- up_heap(parent);
- }
- return;
- //if(idx%2 == 0){
- //int parent = ()
- //}
- // 8, 7 => 3, 3, 4 => 1
- // 16, 15 => 7, 1, 2 => 0
- }
- void down_heap(int idx){
- int l = (idx*2)+1;
- int r = (idx*2)+2;
- int mn_idx = idx;
- int size = heap.size();
- if(l<size && heap[l]<heap[mn_idx]){
- mn_idx = l;
- }
- if(r<size && heap[r]<heap[mn_idx]){
- mn_idx = r;
- }
- if(mn_idx != idx){
- swap(heap[idx], heap[mn_idx]);
- down_heap(mn_idx);
- }
- }
- void del(){
- swap(heap[0], heap[heap.size()-1]);
- heap.pop_back();
- down_heap(0);
- }
- int main(){
- //freopen("heap.in", "r", stdin);
- cin >> n;
- //cout << getParent(15);
- int a, b;
- for(int i=0; i<n; i++){
- cin >> a;
- if(a==1){
- cin >> b;
- //cout << "b: " << b << '\n';
- heap.push_back(b);
- up_heap(heap.size()-1);
- }else if(a==2){
- cout << heap[0] << '\n';
- }else if(a==3){
- del();
- }
- }
- //cout << heap.size() << '\n';
- //print_heap();
- //del();
- //cout << "========" << '\n';
- //cout << heap.size() << '\n';
- //print_heap();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement