Cod sursa(job #2743082)

Utilizator MihaiLazar26Lazar Mihai MihaiLazar26 Data 22 aprilie 2021 15:45:50
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.71 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

vector<int> poz;
vector<long long> elem;
vector<long long> heap;

int find_elem(int x)
{
    for(unsigned int i=0; i<elem.size(); i++)
        if(elem[i] == x) return i;
    return -1;
}

int father_of(int i)
{
    if(i==0) return -1;
    return (i-1)/2;
}

int left_child_of(int i)
{
    return i*2+1;
}

int right_child_of(int i)
{
    return i*2+2;
}

long long get_minim()
{
    return heap[0];
}

void insert_value(long long x)
{
    heap.push_back(x);
    elem.push_back(x);
    int c = heap.size()-1, f = father_of(c);
    poz.push_back(c);
    while(f != -1 && heap[c] < heap[f])
    {


        int posc = find_elem(heap[c]);
        int posf = find_elem(heap[f]);
        swap(heap[c], heap[f]);
        swap(poz[posc], poz[posf]);

        c = f;
        f = father_of(c);
    }

}

void delete_value(int i)
{
    i--;

    if(poz[i] != -1)
    {
        int f = heap.size()-1;
        int posf = find_elem(heap[f]);

        swap(heap[f], heap[poz[i]]);
        swap(poz[posf], poz[i]);
        heap.pop_back();
        poz[i] = -1;

        f = poz[posf];

        unsigned int lc = left_child_of(f), rc = right_child_of(f);
        while((lc < heap.size() || rc < heap.size()) && (heap[f] > heap[lc] || heap[f] > heap[rc]))
        {
            if(lc < heap.size() && heap[f] > heap[lc])
            {
                int posc = find_elem(heap[lc]);
                int posf = find_elem(heap[f]);
                swap(heap[lc], heap[f]);
                swap(poz[posc], poz[posf]);
                f = lc;
                lc = left_child_of(f), rc = right_child_of(f);
            }
            else if(rc < heap.size() && heap[f] > heap[rc])
            {
                int posc = find_elem(heap[rc]);
                int posf = find_elem(heap[f]);
                swap(heap[rc], heap[f]);
                swap(poz[posc], poz[posf]);
                f = rc;
                lc = left_child_of(f), rc = right_child_of(f);
            }
            else break;
        }



    }
}



int main()
{

    int n, op, x;
    fin>>n;
    for(int i=1; i<=n; i++)
    {
        fin>>op;
        switch(op)
        {
        case 1:
        {
            fin>>x;
            insert_value(x);
            break;
        }
        case 2:
        {
            fin>>x;
            delete_value(x);
            break;
        }
        case 3:
        {
            fout<<get_minim()<<"\n";
            break;
        }
        default:
        {
            break;
        }
        }
    }
}