Pagini recente » Cod sursa (job #956383) | Cod sursa (job #2927037) | Cod sursa (job #317013) | Cod sursa (job #1970376) | Cod sursa (job #2299808)
#include <fstream>
using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
const int max_number_of_elements = 200001;
struct Heap_pair{
int value;
int time_key;
} heap[max_number_of_elements];
int time_array[max_number_of_elements];
int current_element_count = 0, time_array_size = 0;
int father_of(int i) {
return i/2;
}
int left_son_of(int i) {
return i * 2;
}
int right_son_of(int i) {
return i * 2 + 1;
}
void swap_in_time_array(int i, int j) {
int temp = time_array[i];
time_array[i] = time_array[j];
time_array[j] = temp;
}
void swap_in_heap(int i, int j) {
Heap_pair temp = heap[i];
heap[i] = heap[j];
heap[j] = temp;
swap_in_time_array(heap[i].time_key, heap[j].time_key);
}
bool percolate(int pos) {
if(father_of(pos) && heap[father_of(pos)].value > heap[pos].value) {
swap_in_heap(pos, father_of(pos));
percolate(father_of(pos));
return true;
}
return false;
}
bool sift(int pos) {
int son = 0;
if (left_son_of(pos) <= current_element_count) {
son = left_son_of(pos);
if (right_son_of(pos) <= current_element_count && heap[right_son_of(pos)].value < heap[son].value)
son = right_son_of(pos);
if(heap[son].value >= heap[pos].value)
son = 0;
}
if (son) {
swap_in_heap(pos, son);
sift(son);
return true;
}
return false;
}
void show_array(int v[], int size_) {
for (int i = 1; i <= size_; ++i)
fout << v[i] << ' ';
fout << '\n';
}
void show_heap(Heap_pair v[], int size_) {
for (int i = 1; i <= size_; ++i)
fout << v[i].value << ' ';
fout << '\n';
}
void op1() {
fin >> heap[++current_element_count].value;
++time_array_size;
heap[current_element_count].time_key = time_array_size;
time_array[time_array_size] = current_element_count;
percolate(current_element_count);
//show_heap(heap, current_element_count);
//show_array(time_array, time_array_size);
//fout << '\n';
}
void op2() {
int x;
fin >> x;
int to_delete = time_array[x];
swap_in_heap(to_delete, current_element_count);
current_element_count--;
if(!percolate(to_delete))
sift(to_delete);
//show_heap(heap, current_element_count);
//show_array(time_array, time_array_size);
//fout << '\n';
}
void op3() {
fout << heap[1].value << '\n';
}
int main()
{
int N;
fin >> N;
for (; N; N--) {
int code;
fin >> code;
switch(code) {
case 1: op1();
break;
case 2: op2();
break;
case 3: op3();
break;
}
}
fin.close();
fout.close();
return 0;
}