Cod sursa(job #2770348)

Utilizator LucaMihaiLM10Luca Ilie LucaMihaiLM10 Data 20 august 2021 16:34:49
Problema Heapuri Scor 0
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.87 kb
#include <stdio.h>

#define MAX_N 200000

int n, heapSize;
int heap[MAX_N], poz[MAX_N], v[MAX_N];

int min( int nod ) {
    int c, p;

    p = nod;

    for ( c = nod * 2 + 1; c <= nod * 2 + 2 && c <= heapSize; c++ ) {
        if ( v[heap[c]] < v[heap[p]] )
            p = c;
    }

    return p;
}

void down( int nod ) {
    int c, aux;

    c = min( nod );
    while ( c > nod ) {
        aux = poz[heap[nod]];
        poz[heap[nod]] = poz[heap[c]];
        poz[heap[c]] = aux;
        aux = heap[nod];
        heap[nod] = heap[c];
        heap[c] = aux;
        c = min( nod );
    }
}

void up( int nod ) {
    int c, aux;

    c = (nod - 1) / 2;
    while ( c >= 0 && v[heap[nod]] < v[heap[c]] ) {
        aux = poz[heap[nod]];
        poz[heap[nod]] = poz[heap[c]];
        poz[heap[c]] = aux;
        aux = heap[nod];
        heap[nod] = heap[c];
        heap[c] = aux;
        c = (nod - 1) / 2;
    }
}

void insertHeap() {
    heap[heapSize] = heapSize;
    poz[n] = heapSize;
    up( heapSize );
    heapSize++;
}

void deleteHeap( int x ) {
    heap[poz[x]] = heap[heapSize - 1];
    poz[heap[heapSize - 1]] = poz[x];
    heapSize--;
    up( poz[x] );
    down( poz[x] );
    poz[x] = -1;
}

int main() {
    FILE *fin, *fout;
    int q, c, x, i;

    fin = fopen( "heapuri.in", "r" );
    fout = fopen( "heapuri.out", "w" );

    fscanf( fin, "%d", &q );
    for ( i = 0; i < q; i++ ) {
        fscanf( fin, "%d", &c );
        if ( c == 1 ) {
            fscanf( fin, "%d", &x );
            v[n] = x;
            insertHeap();
            n++;
        }
        else if ( c == 2 ) {
            fscanf( fin, "%d", &x );
            x--;
            deleteHeap( x );
        }
        else
            fprintf( fout, "%d\n", v[heap[0]] );
    }

    fclose( fin );
    fclose( fout );

    return 0;
}