Cod sursa(job #2180685)

Utilizator 24601Dan Ban 24601 Data 21 martie 2018 01:30:29
Problema Heapuri Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 2.17 kb
#include <stdint.h>
#include <stdio.h>

#define SIZE 2000000

struct elem {
    int x, ins_time;
};

static int time_n, hlen;
static struct elem h[SIZE];
static int pos[SIZE];

static void h_bubble_up(int idx, struct elem v)
{
	struct elem pval;
	int pidx;

	while (idx > 0) {
	    pidx = idx >> 1;

		pval = h[pidx];
		if (pval.x < v.x)
			return;
		h[pidx] = v;
		pos[h[pidx].ins_time] = pidx;
		h[idx] = pval;
		pos[h[idx].ins_time] = idx;
		idx = pidx;
	}
}

static void h_bubble_down(int idx, struct elem v)
{
	struct elem v1, v2;
	int i1, i2;

	while (idx < hlen) {
	    i1 = i2 = idx << 1;
	    i2++;

		if (i1 != i2 && i2 < hlen) {
		    v1 = h[i1];
		    v2 = h[i2];
			if (v1.x < v.x && v1.x <= v2.x) {
			    h[i1] = v;
			    pos[h[i1].ins_time] = i1;
				h[idx] = v1;
			    pos[h[idx].ins_time] = idx;
				idx = i1;
			} else if (v2.x < v.x) {
			    h[i2] = v;
			    pos[h[i2].ins_time] = i2;
				h[idx] = v2;
			    pos[h[idx].ins_time] = idx;
				idx = i2;
			} else {
				break;
			}
		} else if (i1 < hlen) {
		    v1 = h[i1];
			if (v1.x < v.x) {
			    h[i1] = v;
			    pos[h[i1].ins_time] = i1;
			    h[idx] = v1;
			    pos[h[idx].ins_time] = idx;
				idx = i1;
			} else {
				break;
			}
		} else {
			break;
		}
	}
}

static void ins(int val)
{
	pos[++time_n] = hlen;
	h[hlen].ins_time = time_n;
	h[hlen].x = val;
	h_bubble_up(hlen, h[hlen]);

	hlen++;
}

static void rm(int ins_time)
{
	h[pos[ins_time]] = h[hlen - 1];
    pos[h[hlen - 1].ins_time] = pos[ins_time];

	h_bubble_down(pos[ins_time], h[pos[ins_time]]);

	hlen--;
	if (hlen == 0) {
		return;
	}
}

static inline int read(void)
{
    int x = 0;
    char buf[14], *p;

    fgets_unlocked(buf, sizeof buf, stdin);
    p = buf;

    while (*p != '\n') {
        x = x * 10 + (*p - '0');
        p++;
    }

    return x;
}

int main(void)
{
    int ch, n = 0;

    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);

    n = read();

    while (n--) {
        ch = getchar_unlocked();
        getchar_unlocked();

        if (ch == '1') {
            ins(read());
        } else if (ch == '2') {
            rm(read());
        } else {
            printf("%d\n", h[0].x);
        }
    }

    return 0;
}