Cod sursa(job #2536025)

Utilizator bigmixerVictor Purice bigmixer Data 1 februarie 2020 13:50:50
Problema Heapuri Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.28 kb
#include <bits/stdc++.h>
#define ll long long
#define all(a) (a).begin(), (a).end()
//#pragma GCC optimize("O3")
//#pragma GCC optimize("Ofast")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#define sz() size()
#define fr first
#define sc second
#define pb push_back
#define er erase
#define in insert
#define pi pair<int,int>
#define pii pair<pair<int,int>,int>
#define mp make_pair
#define int long long
#define rc(s) return cout<<s,0
#define rcc(s) cout<<s,exit(0)
using namespace std;

int T,op,n,timp,tin[200005],postin[200005];
vector<int>heap;

void insert(int n){
    heap.push_back(n);
    tin[heap.size()-1]=(++timp);
    postin[timp]=heap.size()-1;
    int pos=heap.size()-1;
    while(pos>=2 && heap[pos/2]>heap[pos]){
        swap(heap[pos/2],heap[pos]);
        swap(tin[pos],tin[pos/2]);
        swap(postin[tin[pos]],postin[tin[pos/2]]);
        pos=pos/2;
    }
    return ;
}

void delet(int n){
    int pos=postin[n];
    swap(heap[heap.size()-1],heap[pos]);
    swap(tin[heap.size()-1],tin[pos]);
    swap(postin[tin[heap.size()-1]],postin[tin[pos]]);
    heap.pop_back();
    if(pos==heap.size()) return;
    while((2*pos<heap.size() && heap[2*pos]<heap[pos]) || (2*pos+1<heap.size() && heap[2*pos+1]<heap[pos])){
        int pos1=0;
        int mini=heap[pos];
        if(2*pos+1<heap.size() && heap[2*pos+1]<heap[pos]){
            pos1=2*pos+1;
            mini=heap[2*pos+1];
        }
        else if(heap[2*pos]<mini){
            pos1=2*pos;
        }
        swap(heap[pos1],heap[pos]);
        swap(tin[pos],tin[pos1]);
        swap(postin[tin[pos]],postin[tin[pos1]]);
        pos=pos1;
    }
    return;
}

int32_t main(){
   // ios_base::sync_with_stdio(false);cin.tie(0);cerr.tie(0);cout.tie(0);
    //srand(chrono::steady_clock::now().time_since_epoch().count());
    ifstream cin("heapuri.in");
    ofstream cout("heapuri.out");
    cin >> T;
    heap.push_back(0);
    while(T--){
        cin >> op;
        if(op==1){
            cin >> n;
            insert(n);
        }
        if(op==2){
            cin >> n;
            delet(n);
        }
        if(op==3) cout << heap[1] << '\n';
     //   for(auto i:heap) cout << i << ' ';
       // cout << '\n';
    }
    return 0;
}