Cod sursa(job #2622934)

Utilizator Sho10Andrei Alexandru Sho10 Data 2 iunie 2020 11:14:59
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.91 kb
#include <bits/stdc++.h> //Andrei Alexandru a.k.a Sho10
#define ll long long
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#define all(a) (a).begin(), (a).end()
#define sz size
#define f first
#define s second
#define pb push_back
#define er erase
#define in insert
#define mp make_pair
#define pi pair
#define rc(s) return cout<<s,0
#define endl '\n'
#define mod 1000000007
#define modul 998244353
#define PI 3.14159265359
#define CODE_START  ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
ll t,n,a[200005],pos[200005],m;
vector<ll>heap;
void ins(ll val){
heap.pb(val);
++m;
a[heap.size()-1]=m;
pos[m]=heap.size()-1;
ll p=heap.size()-1;
while(p>=2&&heap[p/2]>heap[p]){
    swap(heap[p],heap[p/2]);
    swap(a[p],a[p/2]);
    swap(pos[a[p/2]],pos[a[p]]);
p=p/2;
}
return ;
}
void del(ll val){
ll p=pos[val];
if(p==heap.size()-1){
    heap.pop_back();
    return;
}
swap(heap[heap.size()-1],heap[p]);
swap(a[p],a[heap.size()-1]);
swap(pos[a[heap.size()-1]],pos[a[p]]);
heap.pop_back();
while(p>=2&&heap[p/2]>heap[p]){
     swap(heap[p],heap[p/2]);
    swap(a[p],a[p/2]);
    swap(pos[a[p/2]],pos[a[p]]);
p=p/2;
}
while((2*p<heap.size()&&heap[2*p]<heap[p])||(2*p+1<heap.size()&&heap[2*p+1]<heap[p])){
    ll pos1=0;
    ll mn=heap[p];
    if(2*p+1<heap.size()&&heap[2*p+1]<heap[p]){
        pos1=2*p+1;
        mn=heap[p*2+1];
    }
    if(heap[2*p]<mn){
        pos1=2*p;
    }
         swap(heap[p],heap[pos1]);
    swap(a[p],a[pos1]);
    swap(pos[a[pos1]],pos[a[p]]);
p=pos1;
if(p==0){
    return;
}

}
return ;
}
int32_t main(){
CODE_START;
ifstream cin("heapuri.in");
ofstream cout("heapuri.out");
cin>>t;
heap.pb(0);
while(t--){
    ll q;
    cin>>q;
    if(q==1){
        ll x;
        cin>>x;
        ins(x);
    }else if(q==2){
    ll x;
    cin>>x;
    del(x);
    }else {
    cout<<heap[1]<<endl;
}
}
}