Cod sursa(job #2180691)

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

#define SIZE 2000000
#define CH_SIZE 12

struct ch_elem {
    int x;
    char ch[CH_SIZE];
};

struct elem {
    struct ch_elem x;
    int ins_time;
};

static int time_n, hlen;
static struct elem h[SIZE];
static int pos[SIZE];
static char buf[CH_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.x < v.x.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.x < v.x.x && v1.x.x <= v2.x.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.x < v.x.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.x < v.x.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.x = val;
	memcpy(h[hlen].x.ch, buf, CH_SIZE);
	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 ch, i, x = 0;

    i = 0;
    while ((ch = getchar_unlocked()) != '\n') {
        buf[i++] = ch;
        x = x * 10 + (ch - '0');
    }
    buf[i] = '\0';

    return x;
}

static inline void write(void)
{
    int i;

    for (i = 0; h[0].x.ch[i] != '\0'; i++) {
        putchar_unlocked(h[0].x.ch[i]);
    }
    putchar_unlocked('\n');
}

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 {
            write();
        }
    }

    return 0;
}