Cod sursa(job #2921708)

Utilizator OvidRata Ovidiu Ovid Data 1 septembrie 2022 14:58:33
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.63 kb
#include<bits/stdc++.h>
using namespace std;

string numeFisier="heapuri";
ifstream fin(numeFisier+".in"); ofstream fout(numeFisier+".out");
#define cin fin
#define cout fout

#define INIT  ios_base :: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define mp make_pair
#define pb push_back
#define ft first
#define sc second
#define ll long long
#define pii pair<int, int>
#define count_bits __builtin_popcount
//#define int ll


int m, a[300010];


int sz=0;
int heap[400010];
int nod[400010];

void add(int x, int ord){
sz++;
heap[sz]=ord;
nod[ord]=sz;
int u=sz;
while(u>1){
    if(a[heap[u] ]<a[heap[u/2 ] ]){
        swap(heap[u], heap[u/2] );
        swap(nod[heap[u] ], nod[heap[u/2] ] );
        u/=2;
    }
    else{
        break;
    }
}

}

void del(int ord){

int x=a[ord];
int u=nod[ord];
if(u==sz){
    sz--; return;
}
swap(heap[sz], heap[u]);
swap(nod[heap[sz] ], nod[heap[u] ]);
heap[sz]=-1;
sz--;
while(true){
    if(u>1){
    if(a[heap[u]]<a[heap[u/2]] ){
        swap(heap[u], heap[u/2]);
        swap(nod[heap[u] ], nod[heap[u/2] ]);
        u/=2;
        continue;
    }
    }
    int l=u*2, r=u*2+1;
    if(r>sz){
        if(l>sz){
            break;
        }
        else{
            if(a[heap[u]]>a[heap[l]]){
                swap(heap[u], heap[l]);
                swap(nod[heap[u]], nod[heap[l]]);
                u=l;
                continue;
            }
            else{
                break;
            }
        }
    }
    else{
        if(a[heap[l]]<a[heap[r]]){
            if(a[heap[l]]<a[heap[u]]){
                swap(heap[l], heap[u]);
                swap(nod[heap[l] ], nod[heap[u] ]);
                u=l;
                continue;
            }
            else{
                break;
            }
        }
        else{
            if(a[heap[r]]<a[heap[u]]){
                swap(heap[r], heap[u]);
                swap(nod[heap[r]], nod[heap[u]]);
                u=r;
                continue;
            }
            else{
                break;
            }
        }
    }

}



}

int32_t main(){
INIT
cin>>m;
for(int i=1; i<=2*m; i++){
    heap[i]=-1;
}
int cnt=0;

for(int i=1; i<=m; i++){
    int tp;
    cin>>tp;
    switch( tp){
    case 1: int x; cin>>x; cnt++; a[cnt]=x; add(x, cnt); break;
    case 2: int ord; cin>>ord; del(ord); break;
    case 3: cout<<a[heap[1]]<<"\n"; break;
    }
    /*
    for(int i=1; i<=sz; i++){
        cout<<a[heap[i]]<<" ";
    }
    cout<<"\n";
    */

}


return 0;
}