Pagini recente » Cod sursa (job #2459507) | Cod sursa (job #1603758) | Cod sursa (job #2724304) | Cod sursa (job #1902560) | Cod sursa (job #489415)
Cod sursa(job #489415)
#include <stdio.h>
//#define NMAX 2003
//#define ELMAX 100001
#define NMAX 200003
FILE *fin, *fout;
int nr;
int heap[NMAX], heaplen, elems[NMAX], elemslen;
int pos[NMAX];
void swap(int i, int j) {
int aux;
pos[heap[i]] = j;
pos[heap[j]] = i;
aux = heap[i];
heap[i] = heap[j];
heap[j] = aux;
}
void remove_elem(int i) {
int father, son, current;
if (i == heaplen - 1) {
pos[heap[i]] = 0;
heaplen--;
return;
}
current = i;
father = i/2;
while (current > 1) {
//printf("swapping %d and %d\n", heap[father], heap[current]);
swap(father, current);
current = father;
father = current/2;
}
//printf("replacing %d with %d\n", heap[1], heap[heaplen-1]);
heap[1] = heap[heaplen - 1];
pos[heap[1]] = 1;
heaplen--;
current = 1;
son = current * 2;
while (son < heaplen) {
if ((son + 1) == heaplen) {
if (elems[heap[son]] < elems[heap[current]]) swap(son, current);
break;
}
if (elems[heap[son]] > elems[heap[current]] && elems[heap[son + 1]] > elems[heap[current]]) break;
if (elems[heap[son]] > elems[heap[son + 1]]) son++;
//printf("swapping %d and %d\n", heap[son], heap[current]);
swap(son, current);
current = son;
son = current * 2;
}
}
void insert_elem(int elem) {
int father, current;
heap[heaplen] = elem;
pos[elem] = heaplen;
current = heaplen;
father = heaplen/2;
while (elems[heap[father]] > elems[heap[current]] && father > 0) {
swap(father, current);
current = father;
father = current/2;
}
heaplen++;
}
void print_heap() {
int i;
for (i = 1; i < heaplen; i++) printf("%d ", elems[heap[i]]);
printf("\n");
}
int get_min() {
return elems[heap[1]];
}
int main() {
int i, code, elem;
fin = freopen("heapuri.in", "r", stdin);
fout = freopen("heapuri.out", "w", stdout);
scanf("%d", &nr);
elemslen = 1;
heaplen = 1;
for (i = 0; i < nr; i++) {
//printf("---------------------\n");
scanf("%d", &code);
switch (code) {
case 1:
scanf("%d", &elem);
elems[elemslen] = elem;
//printf("insert %d\n", elemslen);
insert_elem(elemslen);
elemslen++;
//print_heap();
break;
case 2:
scanf("%d", &elem);
//printf("remove from %d\n", pos[elem]);
remove_elem(pos[elem]);
//print_heap();
break;
case 3:
printf("%d\n", get_min());
break;
}
}
return 0;
}