Cod sursa(job #2931101)

Utilizator MrPuzzleDespa Fabian Stefan MrPuzzle Data 30 octombrie 2022 14:57:38
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.07 kb
#include<fstream>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<climits>
#include<iomanip>
#include<cstring>
#include<bitset>

#define MAX 100000

using namespace std;

ifstream f("heapuri.in");
ofstream g("heapuri.out");

//ifstream f("in.in");
//ofstream g("out.out");

int m,t,x;
int n,k=0;

int v[200005],h[200005],p[200005];

int father(int x){
    return x/2;
}

int leftSon(int x){
    return x*2;
}

int rightSon(int x){
    return x*2+1;
}


void upHeap(int poz){

    while(v[h[poz]] < v[h[father(poz)]] && poz>1){

        swap(h[poz],h[father(poz)]);
        p[h[poz]] = poz;
        p[h[father(poz)]] = father(poz);

        poz = father(poz);
    }
}

void downHeap(int poz){
    int chosenSon = 0;

    do{
        chosenSon = 0;
        if(leftSon(poz) <= n){
            chosenSon = leftSon(poz);

            if(rightSon(poz) <= n && v[h[rightSon(poz)]] < v[h[chosenSon]]){
                chosenSon = rightSon(poz);
            }

            if(chosenSon >= v[h[poz]]){
                chosenSon = 0;
            }
        }

        if(chosenSon!=0){

            swap(h[poz],h[chosenSon]);
            p[h[poz]] = poz;
            p[h[chosenSon]] = chosenSon;

            poz = chosenSon;
        }

    }while(chosenSon!=0);
}

void cut(int poz){
    swap(h[poz],h[n]);
    p[h[poz]] = poz;
    p[h[n]] = n;
    n--;

    if(poz>1 && h[poz]<h[father(poz)]){
        upHeap(poz);
    }else{
        downHeap(poz);
    }
}

void insertt(int x){
    k++;
    v[k] = x;
    n++;
    p[k] = n;
    h[n] = k;

    upHeap(n);
}

int main(){

    f>>m;
    for(int i=1;i<=m;i++){
        f>>t;
        if(t==1){
            f>>x;

            insertt(x);
        }else if(t==2){
            f>>x;

            cut(p[x]);
        }else if(t==3){
            g<<v[h[1]]<<'\n';
        }

        /*cout<<i<<": ";
        for(int i=1;i<=n;i++){
            cout<<v[h[i]]<<" ";
        }
        cout<<'\n';*/
    }


    f.close();
    g.close();
    return 0;
}