Pagini recente » Cod sursa (job #204400) | Cod sursa (job #792714) | Cod sursa (job #2103282) | Cod sursa (job #2300926) | Cod sursa (job #2002883)
#include <cstdio>
#include <vector>
using namespace std;
vector<int> vals, heap, poses;
int n, size_heap, size_insert;
void swap(int p1, int p2){
int aux = heap[p1];
heap[p1] = heap[p2];
heap[p2] = aux;
aux = poses[heap[p1]];
poses[heap[p1]] = poses[heap[p2]];
poses[heap[p2]] = aux;
}
void heap_sus(int p){
if(p == 1)
return;
if(vals[heap[p]] < vals[heap[p / 2]]){
swap(p, p / 2);
heap_sus(p / 2);
}
}
void heap_jos(int p){
int new_p = 0;
if(2 * p <= size_heap && vals[heap[p]] > vals[heap[2 * p]])
new_p = 2 * p;
if((2 * p + 1 <= size_heap && vals[heap[2 * p]] > vals[heap[2 * p + 1]]) && vals[heap[p]] > vals[heap[2 * p + 1]])
new_p = 2 * p + 1;
if(new_p != 0){
swap(p, new_p);
heap_jos(new_p);
}
}
void insert_el(int news){
size_insert++;
int last = size_insert;
vals.push_back(news);
heap.push_back(last);
size_heap++;
poses[last] = size_heap;
heap_sus(poses[last]);
}
void sterg(int pos){
swap(poses[pos], size_heap);
size_heap--;
heap.pop_back();
heap_sus(pos);
heap_jos(pos);
}
int main(){
FILE *fin, *fout;
fin = fopen("heapuri.in", "r");
fout = fopen("heapuri.out", "w");
fscanf(fin, "%d", &n);
int command, new_el, pos;
vals.push_back(0);
poses.push_back(0);
heap.push_back(0);
for(int i = 1;i <= n;i++){
fscanf(fin, "%d", &command);
if(command == 1){
fscanf(fin, "%d", &new_el);
insert_el(new_el);
fprintf(fout, "New element inserted: %d\n", new_el);
}
else if(command == 2){
fscanf(fin, "%d", &pos);
fprintf(fout, "Element on pos %d deleted\n", pos);
sterg(pos);
}
else
fprintf(fout, "New min is %d\n", vals[heap[1]]);
for(int j = 1;j < vals.size();j++)
fprintf(fout, "%d ",vals[j]);
fprintf(fout, "\n");
for(int j = 1;j <= size_heap;j++)
fprintf(fout, "%d ",heap[j]);
fprintf(fout, "\n");
for(int j = 1;j <= size_insert;j++)
fprintf(fout, "%d ",poses[j]);
fprintf(fout, "\n");
}
return 0;
}