Cod sursa(job #2760078)

Utilizator ioana2008vIoana Velniceru ioana2008v Data 22 iunie 2021 19:24:52
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.1 kb
#include <iostream>
#include <fstream>

using namespace std;

const int N = 200001;
int heap[N], pozitie[N], nr_el, v[N];

void urcare(int poz){
    while (v[heap[poz]] < v[heap[(poz - 1)/ 2]]){
        int aux = heap[(poz - 1) / 2];
        heap[(poz - 1) / 2] = heap[poz];
        heap[poz] = aux;
        pozitie[heap[(poz - 1) / 2]] = (poz - 1) / 2;
        pozitie[heap[poz]] = poz;
        poz  = (poz - 1) / 2;
    }
}

void coborare(int poz){
    int fiu, p = poz;
    fiu = poz * 2 + 1;
    if (fiu < nr_el && v[heap[fiu]] < v[heap[p]]){
        p = fiu;
    }
    fiu = poz * 2 + 2;
    if (fiu < nr_el && v[heap[fiu]] < v[heap[p]]){
        p = fiu;
    }
    if (p != poz){
        int aux = heap[poz];
        heap[poz] = heap[p];
        heap[p] = aux;
        pozitie[heap[p]] = p;
        pozitie[heap[poz]] = poz;
        coborare(p);
    }
}

void inserare(int el){
    heap[nr_el++] = el;
    pozitie[el] = nr_el - 1;
    urcare(nr_el - 1);
}

void stergere(int poz){
    ///inlocuire cu elementul de dupa heap
    if (poz == nr_el - 1)
    {
        nr_el--;
    }
    else
    {
        heap[poz] = heap[nr_el - 1];
        nr_el--;
        pozitie[heap[poz]] = poz;
        coborare(poz);
        urcare(poz);
    }
    ///heap[pozitie[poz]] = heap[nr_el++]; ??
    ///heap[pozitie[poz]] = heap[nr_el]; nr_el--; ??
    coborare(pozitie[poz]);
}

int main()
{
    ifstream fi ("heapuri.in");
    ofstream fo ("heapuri.out");
    int nr_op, n = 0;
    fi >> nr_op;
    for (int i = 0; i < nr_op; i++){
        int tip;
        fi >> tip;
        if (tip == 1){
            int x;
            fi >> x;
            v[n++] = x;
            inserare(n - 1);
        } else if (tip == 2){
            int x;
            fi >> x;
            x--;
            stergere(pozitie[x]);
        } else {
            fo << v[heap[0]] << "\n";
        }
        /*
        for (int j = 0; j < nr_el; j++)
        {
            fo << v[heap[j]] << " ";
        }
        fo << "\n";
    */
    }
    fi.close();
    fo.close();
    return 0;
}