Cod sursa(job #1937922)

Utilizator sulzandreiandrei sulzandrei Data 24 martie 2017 13:47:05
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.51 kb
#include <iostream>
#include <fstream>
#include <set>
#include <algorithm>
using namespace std;

ifstream f("heapuri.in");
ofstream g("heapuri.out");
void solveA()
{
    set<int> myset;
    int t,pos[200003],x,op,i=0;
    f>>t;
    while(t--)
    {
        f>>op;
        switch(op)
        {
        case 1:
            i++;
            f>>x;
            myset.insert(x);
            pos[i] = x;
            break;
        case 2:
            f>>x;
            myset.erase(pos[x]);
            break;
        case 3:
                g<<*myset.begin()<<'\n';
            break;
        }
    }
}

constexpr int MAX_E = 200003;
// posi[i] the i-th inserted element's position in the heap, we use this so we know where is in the heap the el to delete
// heap[i] the element in the heap at pos i
// insi[i] the element on position i in the heap ,it's insertion time, we use this so we keep track of posi
int posi[MAX_E],insi[MAX_E];
int father(int i){return i/2;}
int lson(int i){return 2*i;}
int rson(int i){return 2*i+1;}
void rise(int *h,int k)
{
    while(k>1 && h[k]<h[father(k)])
    {
        swap(insi[k],insi[father(k)]);
        swap(posi[insi[father(k)]],posi[insi[k]]);
        swap(h[k],h[father(k)]);
        k = father(k);
    }
}
void insert(int *h,int x,int &n,int time)
{
    n++;
    h[n] = x;
    insi[n] = time;
    posi[time] = n;
    rise(h,n);
}
void pushdown(int *h,int k,int n)
{
    int pos=k;
    int posmin = pos;
    while(1)
    {
        posmin = pos;
        if(lson(pos)<= n && h[lson(pos)]<h[pos])
            pos = lson(pos);
        if(rson(pos)<= n && h[rson(pos)]<h[pos])
            pos = rson(pos);
        if(pos!=posmin)
        {
            swap(insi[pos],insi[father(pos)]);
            swap(posi[insi[father(pos)]],posi[insi[pos]]);
            swap(h[pos],h[father(pos)]);
        }
        else
            break;
    }
}

void remove(int *h,int time,int &n)
{
    int pos = posi[time];
    std::swap(h[pos],h[n]);
    n--;
    pushdown(h,pos,n);
}
void solveB()
{
    int heap[MAX_E],n=0,t,x,op,i=0;
    f>>t;
    while(t--)
    {
        f >> op;
        switch(op)
        {
        case 1:
            i++;
            f>>x;
            insert(heap,x,n,i);
            break;
        case 2:
            f>>x;
            remove(heap,x,n);
            break;
        case 3:
            g<<heap[1]<<'\n';
            break;
        }
    }

}
int main()
{
    //solveA();
    solveB();
    return 0;
}