Pagini recente » Cod sursa (job #2828846) | Cod sursa (job #204528) | Cod sursa (job #189918) | Cod sursa (job #2425808) | Cod sursa (job #2370768)
#include <cstdio>
#include <vector>
#include <set>
#define ADD 1
#define DELETE 2
#define MIN 3
#define N_MAX 200001
using namespace std;
int N, operation, value, position, values[N_MAX], valuesSize = 0, heapPosition[N_MAX], heapSize = 0;
pair<int, int> heap[N_MAX];
inline int father(int position) {
return (1 + position) / 2 - 1;
}
inline int leftSon(int position) {
return 2 * position + 1;
}
inline int rightSon(int position) {
return 2 * position + 2;
}
void heapInsert(pair<int, int>* heap, int& heapSize, int value, int position, int* heapPosition) {
heap[heapSize].first = value;
heap[heapSize].second = position;
heapPosition[position] = heapSize++;
while (0 < heapPosition[position]) {
int fatherPosition = father(heapPosition[position]);
if (heap[fatherPosition].first < value) {
break;
}
heapPosition[heap[fatherPosition].second] = heapPosition[position];
std:swap(heap[heapPosition[position]], heap[fatherPosition]);
heapPosition[position] = fatherPosition;
}
}
void heapDelete(pair<int, int>* heap, int& heapSize, int position, int* heapPosition) {
--heapSize;
heapPosition[heap[heapSize].second] = heapPosition[position];
std::swap(heap[heapSize], heap[heapPosition[position]]);
int target = heapPosition[position];
heapPosition[position] = -1;
while (leftSon(target) < heapSize) {
int leftSonPosition = leftSon(target);
if (heap[leftSonPosition].first < heap[target].first) {
heapPosition[heap[leftSonPosition].second] = target;
heapPosition[heap[target].second] = leftSonPosition;
std::swap(heap[target], heap[leftSonPosition]);
} else {
int rightSonPosition = rightSon(target);
if (rightSonPosition < heapSize && heap[rightSonPosition].first < heap[target].first) {
heapPosition[heap[rightSonPosition].second] = target;
heapPosition[heap[target].second] = rightSonPosition;
std::swap(heap[target], heap[rightSonPosition]);
} else {
break;
}
}
}
}
int main() {
freopen("heapuri.in", "r", stdin);
freopen("heapuri.out", "w", stdout);
scanf("%d", &N);
while (N--) {
scanf("%d", &operation);
switch (operation) {
case ADD: {
scanf("%d", &value);
values[valuesSize] = value;
heapInsert(heap, heapSize, value, valuesSize++, heapPosition);
break;
}
case DELETE: {
scanf("%d", &position);
heapDelete(heap, heapSize, position - 1, heapPosition);
break;
}
case MIN: {
printf("%d\n", heap[0].first);
break;
}
}
}
return 0;
}