Cod sursa(job #1563309)

Utilizator ericptsStavarache Petru Eric ericpts Data 5 ianuarie 2016 21:37:38
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.85 kb
#include <fstream>
#include <vector>

using namespace std;

const int MAX_N = 2e5 + 10;

struct entry {
    int val;
    int poz;

    entry():
        val(0),
        poz(0) {

        }

    entry(int val, int poz):
        val(val),
        poz(poz) {

        }

    bool operator< (const entry &x) const {
        return val < x.val;
    }
};

bool u[MAX_N];

bool bad(const entry &e) {
    return u[e.poz];
}

template<typename T>
struct heap {
public:
   T v[MAX_N];
   int n;

   heap():
       n(0) {

       }

   const T top() const {
       return v[1];
   }

   void pop() {
       swap(v[1], v[n]);
       n--;
       fall(1);
   }

   void insert(const T& x) {
       ++n;
       v[n] = x;
       raise(n);
   }

private:

   void raise(const int poz) {
       if(poz == 1)
           return;

       if(v[poz] < v[poz / 2]) {
           swap(v[poz], v[poz / 2]);
           return raise(poz / 2);
       }
   }

   void fall(const int poz) {
       int choose = poz;
       const int base = 2 * poz;
       for(int i = 0; i <= 1 && base + i <= n; ++i) {
           if(v[base + i] < v[choose])
               choose = base + i;
       }
       if(choose != poz) {
           swap(v[poz], v[choose]);
           return fall(choose);
       }
   }
};

heap<entry> H;
ifstream in("heapuri.in");

void insert() {
    int x;
    static int poz = 1;
    in >> x;
    H.insert(entry(x, poz));
    ++poz;
}

void erase() {
    int x;
    in >> x;
    u[x] = 1;
}

int top() {
    while(bad(H.top())) {
        H.pop();
    }
    return H.top().val;
}

int main() {
    ofstream out("heapuri.out");
    int n;
    in >> n;
    for(int i = 1; i <= n; ++i) {
        int type;
        in >> type;
        if(type == 1)
            insert();
        else if(type == 2)
            erase();
        else
            out << top() << "\n";
    }
    in.close();
    out.close();
    return 0;
}