Cod sursa(job #2239919)

Utilizator bigmixerVictor Purice bigmixer Data 11 septembrie 2018 23:52:50
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.29 kb
#include <iostream>
#include <fstream>
#define MAXN 200005
 
using namespace std;
 
ifstream in("heapuri.in");
ofstream out("heapuri.out");
 
const int INF = 2e9;
 
int n,elem;
int heap[MAXN],heap_to_v[MAXN],v_to_heap[MAXN];
/*
    v - elemente din v[i] = al i-lea numar citit
    heap - elementele din heap heap[i] = al i-lea numar din heap
    v_to_heap - pozitia pe care se afla elementul v[i] in heap
    heap_to_v - pozitia pe care se afla elementul heap[i] in v
    n - nr elemente din heap
    elem - nr elemente din v
*/
 
void afis(){
    for(int i = 1; i <= n; i++)
        cout<<heap[i]<<" ";
    cout<<"\n";
    for(int i = 1; i <= n; i++)
        cout<<heap_to_v[i]<<" ";
    cout<<"\n"<<"===================="<<"\n";
    for(int i = 1; i <= elem; i++)
        cout<<v_to_heap[i]<<" ";;
    cout<<"\n"<<"===================="<<"\n";
    cout<<"===================="<<"\n";
}
void heap_init(){
    for(int i = 1; i < MAXN; i++)
        heap[i] = INF;
}
void heap_swap(int i,int j){
    v_to_heap[heap_to_v[i]] = j;
    v_to_heap[heap_to_v[j]] = i;
    swap(heap[i],heap[j]);
    swap(heap_to_v[i],heap_to_v[j]);
 
}
void heap_up(int i){
    while(i != 1 && heap[i] < heap[i / 2]){
        heap_swap(i,i / 2);
        i /= 2;
    }
}
void heap_down(int i){
 
    int left = i * 2,right = i * 2 + 1;
    while(i != n && heap[i] != INF && (heap[i] > heap[left] || heap[i] > heap[right])){
        if(heap[left] < heap[right]){
            heap_swap(i,left);
            i = left;
        }else{
            heap_swap(i,right);
            i = right;
        }
        left = i * 2,right = i * 2 + 1;
    }
}
void heap_insert(int nr){
    n++,elem++;
    heap[n] = nr;
    v_to_heap[elem] = n;
    heap_to_v[n] = elem;
    heap_up(n);
}
 
void heap_erase(int nr){
 
    int poz = v_to_heap[nr];
    heap_swap(n,poz);
    heap[n] = INF;
    n--;
 
    heap_up(poz);
    heap_down(poz);
}
 
 
int main()
{
    int q,op;
    in>>q;
 
    heap_init();
 
 
    for(int i = 1; i <= q; i++){
        in>>op;
        int x;
        if(op != 3)
            in>>x;
        if(op == 1)
            heap_insert(x);
        else if(op == 2)
            heap_erase(x);
        else
            out<<heap[1]<<"\n";
    }
 
    return 0;
}