Cod sursa(job #2051098)

Utilizator xRoALexBirtoiu Alexandru xRoALex Data 28 octombrie 2017 15:37:11
Problema Heapuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.73 kb
#include <bits/stdc++.h>
using namespace std;

/* struct Node {
    int data;
    Node *pred, *next;
}; */

FILE *f=fopen("heapuri.in","r");
FILE *g=fopen("heapuri.out","w");

const int Nmax = 200001;
int N;
int n,k;

int v[Nmax],poz[Nmax],ord[Nmax];

/// insert x
/// find max (find top)
/// delete top (pop)

/// pentru nodul aflat la pozitia i ai fii (2*i) si (2*i+1)

/// UP HEAP
/// DOWN HEAP

void superswap(int idx, int idy) {
     swap(v[poz[idx]], v[poz[idy]]);
     swap(poz[idx],poz[idy]);
     /// swap unde[cine[idx]] unde[cine[idy]]
     /// swap cine[idx] cine[idy]
}

void upheap(int index) {
    if(index > 1 && v[index] < v[index/2]) {
        superswap(v[index], v[index/2]);
        upheap(index/2);
    }
}

void downheap(int index) {
    if(2*index+1 <= N && v[2*index+1] < v[index] && v[2*index+1] <= v[2*index]) {
        superswap(v[2*index+1], v[index]);
        downheap(2*index+1);
    }
    if(2*index <= N && v[2*index] < v[index]) {
        superswap(v[2*index], v[index]);
        downheap(2*index);
    }
}

void ins(int x) {
    v[++N] = x;
    ord[++k]=x;
    poz[ord[k]]=N;
    upheap(N);
}

void popx(int x) {
    int p = poz[ord[x]];
    superswap(v[poz[ord[x]]], v[N]);
    N--;
    downheap(p);
    upheap(p);
}

void pop() {
    popx(1);
}

int top() {
    return v[1];
}

int main() {
    fscanf(f,"%d",&n);
    while(n)
    {
        int x,y;
        fscanf(f,"%d",&x);
        if(x==3)
            fprintf(g,"%d\n",top());
        else
        {
            fscanf(f,"%d",&y);
            if(x==1)
                    ins(y);
            if(x==2)
                    popx(y);
        }
        n--;
    }
    cout<<'\n';
    return 0;
}