Cod sursa(job #2917812)

Utilizator db_123Balaban David db_123 Data 7 august 2022 20:50:53
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.88 kb
#include <fstream>
#include <vector>
#include <unordered_map>

using namespace std;

ifstream cin("heapuri.in");
ofstream cout("heapuri.out");

#define DIM 2*1e5

int n;
vector<int> heap;
vector<int> fr(DIM);

void read() {
    cin>>n;
}

void solve() {
    heap.push_back(0);
    int a,b,pos,cnt=1;
    while(n--) {
        cin>>a;
        if(a==1) {
            cin>>b;
            fr[cnt]=b;
            heap.push_back(b);
            pos=heap.size()-1;
            while(pos/2>0 && heap[pos]<heap[pos/2]) {
                swap(heap[pos],heap[pos/2]);
                pos/=2;
            }
            cnt++;
        }
        else if(a==2) {
            cin>>b;
            int l=1,r=heap.size()-1,mid,sol;
            while(l<=r) {
                mid=l+(r-l)/2;
                if(heap[mid]<=fr[b]) {
                    if(heap[mid]==fr[b]) {
                        sol=mid;
                    }
                    l=mid+1;
                }
                else {
                    r=mid-1;
                }
            }
            pos=sol;
            // cout<<"pos:"<<pos<<"\n";
            swap(heap[pos],heap[heap.size()-1]);
            heap.pop_back();
            while(pos*2<heap.size()) {
                if(pos*2+1<heap.size()) {
                    if(heap[pos*2]<heap[pos*2+1]) {
                        swap(heap[pos],heap[pos*2]);
                        pos*=2;
                    }
                    else {
                        swap(heap[pos],heap[pos*2+1]);
                        pos=pos*2+1;
                    }
                }
                else if(pos*2<heap.size()){
                    swap(heap[pos],heap[pos*2]);
                    pos*=2;
                }
                else {
                    break;
                }
            }
        }
        else {
            cout<<heap[1]<<"\n";
        }
    }
}

int main() {
 
    read();
    solve();
    return 0;
}