Cod sursa(job #1248143)

Utilizator gabrieligabrieli gabrieli Data 24 octombrie 2014 18:44:37
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.34 kb
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;

inline int left(const int &i)
{ return 2*i + 1; }

inline int right(const int &i)
{ return 2*i + 2; }

inline int parent(const int &i)
{ return (i - 1) / 2; }

vector<int> map_index_to_heap, map_heap_to_index, H;
int hsize;

void heap_up(int i);
void heap_down(int i);

void inserth(int x);
void deleteh(int index);

int main() {
    ifstream fin("heapuri.in");
    ofstream fout("heapuri.out");
    
    int q, op, x, i;
    
    for (fin >> q; q; --q) {
        fin >> op;
        if (op == 1) {
            fin >> x;
            inserth(x);
        }
        else if (op == 2) {
            fin >> i;
            deleteh(i-1);
        }
        else
            fout << H[0] << endl;
    }
    
    return 0;
}

void deleteh(int index) {
    int heapi = map_index_to_heap[index];
    
    H[heapi] = H[hsize-1];
    map_index_to_heap[ map_heap_to_index[hsize-1] ] = heapi;
    map_heap_to_index[heapi] = map_heap_to_index[hsize-1];
    
    hsize--;
    
    heap_down(heapi);
}

void inserth(int x) {
    int index = map_index_to_heap.size(),
        heapi = hsize;
        
    if (hsize == H.size()) {
        H.push_back(x);
        map_heap_to_index.push_back(index);
    }
    else {
        H[hsize] = x;
        map_heap_to_index[heapi] = index;
    }
    
    hsize++;
    map_index_to_heap.push_back(heapi);
    
    heap_up(heapi);
}

void heap_up(int i) {
    while (true) {
        int p = parent(i);
        
        if (i == p) return;
        
        if (H[i] < H[p]) {
            swap(H[i], H[p]);
            
            map_index_to_heap[ map_heap_to_index[i] ] = p;
            map_index_to_heap[ map_heap_to_index[p] ] = i;
            swap(map_heap_to_index[i], map_heap_to_index[p]);
        }
        else return;
        
        i = p;
    }
}

void heap_down(int i) {
    while (true) {
        int min, l = left(i), r = right(i);
        if (l < hsize) min = l;
        else return;
        
        if (r < hsize && H[r] < H[l])
            min = r;
        
        if (H[i] > H[min]) {
            swap(H[i], H[min]);
            
            map_index_to_heap[ map_heap_to_index[i] ] = min;
            map_index_to_heap[ map_heap_to_index[min] ] = i;
            swap(map_heap_to_index[i], map_heap_to_index[min]);
        }
        else return;
        
        i = min;
    }
}