Cod sursa(job #3235320)

Utilizator adelincirciumaruCirciumaru Adelin-Ionut adelincirciumaru Data 17 iunie 2024 03:39:25
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.16 kb
#include <bits/stdc++.h>

using namespace std;

const int Nmax=1e5;
int H[Nmax + 1];
int pozitii[200000], NrNoduri = 0, NrPoz=0;

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

int left_son(int nod){
    return 2*nod;
}

int right_son(int nod){
    return 2*nod+1;
}

void HeapUp(int k){
    while(k>1 && H[k] < H[father(k)]){
        swap(pozitii[k], pozitii[father(k)]);
        swap(H[k], H[father(k)]);
        k = father(k);
    }

}

void HeapDown(int N, int k){
    while(true){
        int son=0;
        if(left_son(k)<=N) {
            son = left_son(k);
            if(right_son(k) <= N && H[right_son(k)] < H[son])
                son = right_son(k);
        }
        if(son && H[son] < H[k]){
            swap(pozitii[son], pozitii[k]);
            swap(H[son], H[k]);
            k = son;
        }else{
            break;
        }
    }
}

void insert(int &N, int value)
{
    H[++N] = value;
    NrPoz++;
    pozitii[N] = NrPoz;
    HeapUp(N);
}

int find_min(){
    return H[1];
}

void extract_min(int &N)
{
    H[1]=H[N];
    N--;
    HeapDown(N, 1);
}

void build(int N){
    for(int i = N/2; i>=1; i--)
        HeapDown(N, i);
}

void Delete(int &N, int k){
    swap(pozitii[k], pozitii[N]);
    swap(H[k], H[N]);
    N--;
    if((k>1) && (H[k]) < H[father(k)])
        HeapUp(k);
    else HeapDown(N, k);
}

void decrease_key(int k, int value){
    H[k]-=value;
    HeapUp(k);
}

void increase_key(int N, int k, int value){
    H[k] += value;
    HeapDown(N, k);
}

int main()
{
    ifstream f("heapuri.in");
    ofstream g("heapuri.out");
    int N, cod, x, p;
    f>>N;
    for (int i=1; i<=N; i++) {
        f >> cod;
        if(cod!=3)
        {
            f>>x;
            if(cod==1){
                insert(NrNoduri, x);
            }
            else {
                for(int j=1; j<=NrNoduri; j++)
                    if(pozitii[j]==x)
                    {
                        p=j;
                        break;
                    }
                Delete(NrNoduri, p);
            }
        }
        else g<<find_min()<<endl;
    }
    return 0;
}