Cod sursa(job #2614370)

Utilizator michael_blazemihai mihai michael_blaze Data 11 mai 2020 17:41:45
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.03 kb
#include <iostream>
    
#define MAX 200005
    
 
    
using namespace std;
    
 
    
int minHeap[MAX], n;
    
int order[MAX], i;
    
int val[MAX];
    
 
    
// order[i] - returneaza nodul in care se afla valorea inserata
    
// al i-lea in multime
    
// val[i] - inversa lui order[i]
    
// returneaza vechimea valorii din nodul i
    
int getRoot() {
    return minHeap[1];
}
    
 
    
void upHeap(int x) {
    int father = x / 2;
    if (father and minHeap[father] > minHeap[x]) {
        swap(minHeap[father], minHeap[x]);
        swap(order[val[father]], order[val[x]]);
        swap(val[father], val[x]);
        upHeap(father);
    }
}
    
 
    
void downHeap(int x) {
    int son = 2 * x;
    
    if (son + 1 <= n and minHeap[son] > minHeap[son + 1]) 
        son ++;

    if (son <= n and minHeap[son] < minHeap[x]) {
        swap(minHeap[son], minHeap[x]);
        swap(order[val[son]], order[val[x]]);
        swap(val[son], val[x]);
    
        downHeap(son);
    }
}
    
void Insert(int x) {
    ++ i;
    ++ n;

    minHeap[n] = x;
    order[i] = n;    
    val[n] = i;

    upHeap(n);   
}
 
    
void Delete(int x) {
    swap(minHeap[n], minHeap[x]);
    swap(order[val[n]], order[val[x]]);
    swap(val[n], val[x]);
    -- n;
    
    downHeap(x);
    upHeap(x);
}
    
int main() {
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);
    
    int t;
    int operation;
    int value;
    
    // ios_base::sync_with_stdio(false);
    // cin.tie(NULL);
    // cout.tie(NULL);
    
    cin >> t;

    while (t --) {
        cin >> operation;
        switch(operation) {
            case 1:
                cin >> value;
                Insert(value);
                break;
            case 2:
                cin >> value;
                Delete(order[value]);
                break;
            case 3:
                cout << getRoot() << '\n';
                break;
        }
    }
    
    return 0;
}