Pagini recente » Cod sursa (job #1981921) | Cod sursa (job #1786765) | Cod sursa (job #2632667) | Cod sursa (job #404503) | Cod sursa (job #612751)
Cod sursa(job #612751)
#define N 262145
#include<fstream.h>
struct heapEl {
int val;
int seqnumber;
};
heapEl heap[N];
int noOfEl;
int posInHeap[N];
int n;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
int parent(int i) {
return i / 2;
}
int left(int i) {
return 2 * i;
}
int right(int i) {
return 2 * i + 1;
}
void heapDown(int i) {
int smallest = left(i);
if (right(i) <= noOfEl) {
if (heap[left(i)].val > heap[right(i)].val) {
smallest = right(i);
}
}
else
if(left(i) > noOfEl) {
smallest = i;
}
if (heap[smallest].val > heap[i].val) smallest = i;
if (smallest != i) {
int pInHeap = posInHeap[heap[i].seqnumber];
posInHeap[heap[i].seqnumber] = posInHeap[heap[smallest].seqnumber];
posInHeap[heap[smallest].seqnumber] = pInHeap;
heapEl aux = heap[i];
heap[i] = heap[smallest];
heap[smallest] = aux;
heapDown(smallest);
}
return;
}
void heapUp(int i) {
while ((heap[i].val < heap[parent(i)].val) && (i > 1)) {
int pInHeap = posInHeap[heap[i].seqnumber];
posInHeap[heap[i].seqnumber] = posInHeap[heap[parent(i)].seqnumber];
posInHeap[heap[parent(i)].seqnumber] = pInHeap;
heapEl aux = heap[i];
heap[i] = heap[parent(i)];
heap[parent(i)] = aux;
i /= 2;
}
}
void insertInHeap(int el, int seqno) {
noOfEl++;
heap[noOfEl].val = el;
heap[noOfEl].seqnumber = seqno;
heapUp(noOfEl);
}
int extractMin() {
return heap[1].val;
}
void deleteHeap(int r) {
int ind = posInHeap[r];
int aux = posInHeap[heap[noOfEl].seqnumber];
posInHeap[heap[noOfEl].seqnumber] = posInHeap[heap[ind].seqnumber];
posInHeap[heap[ind].seqnumber] = aux;
heapEl haux = heap[noOfEl];
heap[noOfEl] = heap[ind];
heap[ind] = haux;
noOfEl--;
heapDown(ind);
}
void solve() {
int tip, el, no = 0;
f >> n;
for(int i = 1; i <= n; i++) {
f >> tip;
if(tip == 1) {
no++;
f >> el;
posInHeap[no] = no;
insertInHeap(el, no);
}
else
if (tip == 2) {
int seqno;
f >> seqno;
deleteHeap(seqno);
}
else {
g << extractMin() << "\n";
}
}
}
int main() {
solve();
return 0;
}