Pagini recente » Cod sursa (job #613927) | Cod sursa (job #2514733) | Cod sursa (job #759364) | Cod sursa (job #2019483) | Cod sursa (job #1202779)
#include<stdio.h>
#define maxDim 200001
#define minim(x,y) (x)<(y)?(x):(y)
int heap[maxDim]; /*minHeap*/
int pozInHeap[maxDim]; /*poz[i] = pozitia in heap a elementului care a fost inserat al i-lea in multime*/
int length=0, 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" pozitia k pana ii gasim un loc(corect) in heap(ul) de lungime length*/
void sift(int k){
if(k >= length){
return;
}
/*
left - fiul stang;
right - fiul drept;
son - fiul cu care se interschimba (min(left, right))
*/
int left = 0, right = 0, son = 0;
/*daca exista fiu stang il punem in left*/
/*daca nu are fiu stang, atunci nu are nici fiu drept*/
if(left_son(k) <= length){
left = left_son(k);
/*daca exista fiu drept il punem in right*/
if(right_son(k) <= length){
right = right_son(k);
son = minim(heap[left], heap[right]);
}
else son = heap[left];
if(heap[k] > heap[son]){
int aux = heap[son];
heap[son] = heap[k];
heap[k] = aux;
sift(son);
}
else return;
}
}
/*se "infiltreaza" pozitia k pana ii gasim un loc(corect) in heap(ul) de lungime length*/
void percolate(int k, int poz){
pozInHeap[poz] = k;
if(k == 1){
return;
}
/*parent = parintele lui k*/
int parent = father(k);
if(heap[k] < heap[parent]){
int aux = heap[parent];
heap[parent] = heap[k];
heap[k] = aux;
percolate(parent, poz);
}
else return;
}
void insert(int k, int poz){
heap[length] = k;
percolate(length, poz);
}
void del(int k, int poz){
heap[k] = heap[length];
length--;
if( (k > 1) && (heap[k] < heap[father(k)] ) ){
percolate(k, poz);
}
else{
sift(k);
}
}
int main(){
freopen("heapuri.in", "r", stdin);
freopen("heapuri.out", "w", stdout);
scanf("%d", &length);
int i, operation, value;
for(i = 1; i <= numOfOperations; i++);
{
scanf("%d", &operation);
if(operation == 1){
/*se insereaza value in heap*/
scanf("%d", &value);
length++;
insert(value, i);
}
else if(operation == 2){
/*se sterge elementul intrat al value-lea in multime, in ordine cronologica*/
scanf("%d", &value);
del(pozInHeap[value], value);
}
else if(operation == 3){
/*se afiseaza minimul din heap*/
printf("%d", heap[1]);
}
}
return 0;
}