Cod sursa(job #1948883)

Utilizator RazvanatorHilea Razvan Razvanator Data 1 aprilie 2017 15:11:12
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.83 kb
#include <fstream>

using namespace std;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

int n,m;
long long s;
int x;
int v[200005],cnt;

int position[200005];

int H[200005];

int father(int nod)
{
    return nod/2;
}

int left_son(int nod)
{
    return 2*nod;
}

int right_son(int nod)
{
    return 2*nod+1;
}

void sift(int K) {
    int son;
    do {
        son = 0;
        if (left_son(K) <=n) {
            son = left_son(K);
            if (right_son(K) >= n && H[right_son(K)] < H[left_son(K)]) {
                son = right_son(K);
            }
            if (H[son] >= H[K]) {
                son = 0;
            }
        }

        if (son) {
            swap(position[H[K]],position[H[son]]);
            swap(H[K], H[son]);
            K = son;
        }
    } while (son);
}

void percolate(int K) {
    int key = H[K];

    while ((K > 1) && (key < H[father(K)])) {
        position[H[K]]=position[H[father(K)]];
        H[K] = H[father(K)];
        K = father(K);
    }

    H[K] = key;
}

void build_Heap()
{
    for (int i=n/2;i>0;--i) {
        sift(i);
    }
}

void cut(int K) {
    H[K] = H[n];
    --n;

    if ((K > 1) && (H[K] < H[father(K)])) {
        percolate(K);
    } else {
        sift(K);
    }
}

void insertion(int key) {
    H[++n] = key;
    position[n]=++cnt;
    percolate(n);
}

int main()
{
    int a,b;
    fin>>x;
    for (int i=0;i<x;i++) {
        fin>>a;
        if (a==1) {
            fin>>b;
            insertion(b);
            v[cnt]=b;
        }
        else if (a==2) {
            fin>>b;
            cut(position[v[b]]);
        }
        else fout<<H[1]<<'\n';
        for (int i=1;i<=n;i++) fout<<H[i]<<" ";
        for (int i=1;i<=n;i++) fout<<position[i]<<" ";
        fout<<endl;
    }
}