Cod sursa(job #1189408)

Utilizator lvamanuLoredana Vamanu lvamanu Data 22 mai 2014 19:23:47
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.27 kb
#include <iostream>
#include <stdio.h>
#include <vector>
#include <map>

using namespace std; 

#define MAXN 200003

int min_heap[MAXN]; 
int order[MAXN]; 
int mapHeapToCron[MAXN]; 
int heapSize = -1; 
int L = -1; 

void swapElementsInHeap(int poz1, int poz2) {
    swap(min_heap[poz1], min_heap[poz2]); 
    int orderPoz1 = mapHeapToCron[poz1]; 
    int orderPoz2 = mapHeapToCron[poz2]; 
    swap(order[orderPoz1], order[orderPoz2]); 
    swap(mapHeapToCron[poz1], mapHeapToCron[poz2]); 
}


void insertInHeap(int x) {
    heapSize++;
    min_heap[heapSize] = x; 
    L++;
    order[L] = heapSize;
    mapHeapToCron[heapSize] = L;
   
    int i = heapSize;
    int parentI = i / 2; 
    while (i > 0 && min_heap[i] < min_heap[parentI]) {
        swapElementsInHeap(i, parentI); 
        i = parentI; 
        parentI = parentI / 2; 
    }    
}
void printMin() {
    printf("%d\n", min_heap[0]); 
}


void min_heapify(int poz) {
    int left = 2 * poz; 
    int right = 2 * poz + 1;
    int smallest;
    if ( left <= heapSize && min_heap[left] < min_heap[poz]) {
        smallest = left;
    } else {
        smallest = poz;
    }
    if (right <= heapSize && min_heap[right] < min_heap[smallest]) {
        smallest = right; 
    }
    if (smallest != poz) {
        swapElementsInHeap(smallest, poz);        
        min_heapify(smallest); 
    }
    
}
void removeTheXElement(int poz) {
    int nodeHeap = order[poz - 1]; 
    int lastIndex = heapSize;
    swapElementsInHeap (nodeHeap, lastIndex);
    heapSize --; 
    //order.pop_back();
   // mapHeapToCron.erase(lastIndex); 
  //  min_heap.erase(min_heap.begin() + lastIndex); 
    min_heapify(nodeHeap); 
}

int main() {
    freopen("heapuri.in", "r", stdin); 
    freopen("heapuri.out", "w", stdout);
    int N; 
    scanf("%d", &N); 
    for (int i = 0; i < N; i++) {
        int op; 
        cin >> op; 
        if (op < 3) {
            int x; 
            scanf("%d", &x); 
            if (op == 1) {
                insertInHeap(x); 
            } else if (op == 2) {
                removeTheXElement(x); 
            }
        } else if (op == 3) {
            printMin(); 
        }
    }
    fclose(stdin); 
    fclose(stdout); 
    
    return 0; 
}