Cod sursa(job #1995749)

Utilizator flaviu_2001Craciun Ioan-Flaviu flaviu_2001 Data 29 iunie 2017 01:02:15
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.89 kb
#include <fstream>

using namespace std;

ifstream fin ("heapuri.in");
ofstream fout ("heapuri.out");
int m, h[300005], add_count, v[300005], r[300005];

void swap(int &x, int &y){
    int aux = x;
    x = y;
    y = aux;
}

int insert_heap(int x, int n)
{
    h[n+1] = x;
    int poz = n+1;
    while(poz != 1 && h[poz] < h[poz/2]){
        swap(h[poz], h[poz/2]);
        v[r[poz/2]] = poz;
        r[poz] = r[poz/2];
        poz /= 2;
    }
    return poz;
}

void remove_from_heap(int p, int n)
{
    swap(h[p], h[n]);
    r[p] = r[n];
    v[r[n]] = p;
    int poz = p;
    while(poz*2 <= n-1 && h[poz] > h[poz*2]){
        if(poz*2 < n-1 && h[poz*2] < h[poz*2+1]){
            swap(h[poz], h[poz*2]);
            swap(v[r[poz]], v[r[poz*2]]);
            swap(r[poz], r[poz*2]);
            poz = poz*2;
        }else if (poz*2 < n-1){
            swap(h[poz], h[poz*2+1]);
            swap(v[r[poz]], v[r[poz*2+1]]);
            swap(r[poz], r[poz*2+1]);
            poz = poz*2+1;
        }else{
            swap(h[poz], h[poz*2]);
            swap(v[r[poz]], v[r[poz*2]]);
            swap(r[poz], r[poz*2]);
            poz = poz*2;
        }
    }
}

int main()
{
    fin >> m;
    int n = 0;
    while(m--){
        int test, x;
        fin >> test;
        if(test != 3)
            fin >> x;
        switch(test){
            case 3:
                fout << h[1] << "\n";
                break;
            case 1:
                v[++add_count] = insert_heap(x, n); //v reprezinta pozitia in heap al elementului adaugat
                r[v[add_count]] = add_count; //r reprezinta al catalea a fost adaugat elementul din pozitia i al heapului
                ++n;
                break;
            case 2:
                remove_from_heap(v[x], n);
                --n;
                break;
            default:
                fout << "datele de intrare is aiurea\n";
        }
    }
    fout.close();
    return 0;
}