Cod sursa(job #2614528)

Utilizator michael_blazemihai mihai michael_blaze Data 11 mai 2020 20:51:15
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.63 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);
    // }
    int father = x / 2;
    while (father) {
        if (minHeap[father] > minHeap[x]) {
            swap(minHeap[father], minHeap[x]);
            swap(order[val[father]], order[val[x]]);
            swap(val[father], val[x]);
        }
        x = x / 2;
        father = x / 2;
    }    
}

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);
    // }

    int son = 2 * x;
    while (son <= n) {
        if (son + 1 <= n and minHeap[son] > minHeap[son + 1])
            son ++;
        if (minHeap[son] < minHeap[x]) {
            swap(minHeap[son], minHeap[x]);
            swap(order[val[son]], order[val[x]]);
            swap(val[son], val[x]);
        }

        x = son;
        son = 2 * 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;
}