Cod sursa(job #2847066)

Utilizator rapidu36Victor Manz rapidu36 Data 10 februarie 2022 10:02:54
Problema Heapuri Scor 100
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <stdio.h>
#include <stdlib.h>
#define N 200001

int v[N], h[N], poz[N], n, nh, n_op;

void schimb(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/2]])
    {
        schimb(p, p/2);
        p /= 2;
    }
}

void coboara(int p)
{
    int fs = 2*p, fd = 2*p + 1, optim = p;
    if (fs <= nh && v[h[fs]] < v[h[optim]])
    {
        optim = fs;
    }
    if (fd <= nh && v[h[fd]] < v[h[optim]])
    {
        optim = fd;
    }
    if (optim != p)
    {
        schimb(optim, p);
        coboara(optim);
    }
}

void adauga(int x)
{
    h[++nh] = x;
    poz[x] = nh;
    urca(nh);
}

void sterge(int p)
{
    if (p == nh)
    {
        nh--;
    }
    else
    {
        schimb(p, nh--);
        urca(p);
        coboara(p);
    }
}

int main()
{
    FILE *in, *out;
    in = fopen("heapuri.in", "r");
    out = fopen("heapuri.out", "w");
    fscanf(in, "%d", &n_op);
    for (int i = 0; i < n_op; i++)
    {
        int tip;
        fscanf(in, "%d", &tip);
        if (tip == 1)
        {
            fscanf(in, "%d", &v[++n]);
            adauga(n);///adauga n in heap (in heap retin pozitiile din v)
        }
        else if (tip == 2)
        {
            int nr;
            fscanf(in, "%d", &nr);
            sterge(poz[nr]);
        }
        else
        {
            fprintf(out, "%d\n", v[h[1]]);
        }
    }
    fclose(in);
    fclose(out);
    return 0;
}