Cod sursa(job #2037956)

Utilizator DiClauDan Claudiu DiClau Data 12 octombrie 2017 23:41:39
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include<stdio.h>
using namespace std;
const int N = 200005;
int poz[N], v[N], h[N], n, nrh;
void schimba (int p1, int p2)
{
    int aux = h[p1];
    h[p1] = h[p2];
    h[p2] = aux;
    poz[h[p1]] = p1;
    poz[h[p2]] = p2;
}
void urca (int p)
{
    while (v[h[p]] < v[h[p >> 1]])
    {
        schimba (p, p >> 1);
        p >>= 1;
    }
}
void coboara (int p)
{
    int fs = 2 * p, fd = 2 * p + 1, bun = p;
    if (fs <= nrh && v[h[p]] < v[h[fs]])
        bun = fs;
    if (fd <= nrh && v[h[p]] < v[h[fd]])
        bun = fd;
    if (bun != p)
    {
        schimba (bun, p);
        coboara (bun);
    }
}
int main ()
{
    FILE *in, *out;
    in = fopen ("heapuri.in", "r");
    out = fopen ("heapuri.out", "w");
    fscanf (in, "%d", &n);
    int i, cerinta, x;
    for (i = 1; i <= n; i++)
    {
        fscanf (in, "%d", &cerinta);
        if (cerinta == 1)
        {
            fscanf (in, "%d", &x);
            nrh++;
            v[nrh] = x;
            h[nrh] = poz[nrh] = nrh;
            urca (nrh);
        }
        if (cerinta == 2)
        {
            fscanf (in, "%d", &x);
            schimba (nrh--, poz[x]);
            nrh--;
            coboara(poz[x]);
        }
        if (cerinta == 3)
            fprintf (out, "%d\n", v[h[1]]);
    }
    return 0;
}