Pagini recente » Cod sursa (job #2453764) | Algoritmiada 2014 - Clasament general, Clasele 9-10 | Istoria paginii utilizator/kiriaccatalin | Anamaria | Cod sursa (job #1203721)
#include<stdio.h>
#define maxDim 200001
#define minim(x,y) (x)<(y) ? (x):(y)
struct H{
int key;
int order;
} heap[maxDim], aux; /*minHeap si variabila auxiliara pentru interschimbare*/
int w[maxDim]; /*w[i] = pozitia in heap a elementului care a fost inserat al i-lea in multime*/
int length, orderN, numOfOperations;
int father(int nod){
return nod/2;
}
int left_son(int nod){
return nod*2;
}
int right_son(int nod){
return nod*2 + 1;
}
/*se "cerne"(coboara) pozitia k pana ii gasim un loc(corect) in heap(ul) de lungime length*/
void sift(int k){
if(k >= length){
return;
}
int son = 0;
int left = left_son(k);
/*daca nu exista fiu stang, nu exista nici fiu drept*/
if(left <= length){
int right = right_son(k);
if(right <= length){
son = minim(heap[left].key, heap[right].key);
}
else son = left;
if(heap[k].key > heap[son].key){
/*notam modificarea pozitiilor*/
w[heap[k].order] = son;
w[heap[son].order] = k;
/*interschimbam valorile*/
aux = heap[k];
heap[k] = heap[son];
heap[son] = aux;
sift(son);
}
else return;
}
}
/*se "infiltreaza"(urca) pozitia k pana ii gasim un loc(corect) in heap(ul) de lungime length*/
void percolate(int k){
if(k == 1)
return;
int parinte = father(k);
if(heap[k].key < heap[parinte].key){
/*marcam schimbarea pozitiilor*/
w[heap[k].order] = parinte;
w[heap[parinte].order] = k;
aux = heap[k];
heap[k] = heap[parinte];
heap[parinte] = aux;
percolate(parinte);
}
else return;
}
void insert(int value){
length++;
heap[length].key = value;
orderN++;
heap[length].order = orderN;
w[orderN] = length;
percolate(length);
}
void del(int k){
heap[k] = heap[length];
w[heap[k].order] = k;
length--;
if ( (k > 1) && (heap[k].key < heap[father(k)].key)) {
percolate(k);
} else {
sift(k);
}
}
int main(){
freopen("heapuri.in", "r", stdin);
freopen("heapuri.out", "w", stdout);
scanf("%d", &numOfOperations);
int i, operation, value;
i = 1;
while(i <= numOfOperations)
{
scanf("%d", &operation);
if(operation == 1){
/*se insereaza value in heap*/
scanf("%d", &value);
insert(value);
}
else if(operation == 2){
/*se sterge elementul intrat al value-lea in multime, in ordine cronologica*/
scanf("%d", &value);
del(w[value]);
}
else if(operation == 3){
/*se afiseaza minimul din heap*/
printf("%d\n", heap[1]);
}
i++;
}
return 0;
}