Pagini recente » Cod sursa (job #2722904) | Cod sursa (job #699497) | Cod sursa (job #1698194) | Cod sursa (job #263636) | Cod sursa (job #2745325)
#include <iostream>
#include <fstream>
#include <vector>
#include <unordered_map>
using namespace std;
ifstream in("heapuri.in");
ofstream out("heapuri.out");
vector < int > heap, introdus;
unordered_map < int, int > Poz;
int n, task, x;
void urca(int poz)
{
while(poz)
{
int tata = (poz - 1) / 2;
if (heap[tata] > heap[poz])
{
swap(Poz[heap[tata]], Poz[heap[poz]]);
swap(heap[tata], heap[poz]);
poz = tata;
}
else break;
}
}
void coboara(int poz)
{
if(poz * 2 + 1 >= heap.size()) return;
if(poz * 2 + 2 >= heap.size() || heap[poz * 2 + 1] < heap[poz * 2 + 2])
if(heap[poz * 2 + 1] < heap[poz])
{
swap(Poz[heap[poz]], Poz[heap[poz * 2 + 1]]);
swap(heap[poz], heap[poz * 2 + 1]);
coboara(poz * 2 + 1);
return;
}
else
if(heap[poz * 2 + 2] < heap[poz])
{
swap(Poz[heap[poz]], Poz[heap[poz * 2 + 2]]);
swap(heap[poz], heap[poz * 2 + 2]);
coboara(poz * 2 + 2);
return;
}
else return;
}
void inserare(int val)
{
heap.push_back(val);
Poz[val] = heap.size() - 1;
urca(heap.size() - 1);
introdus.push_back(val);
}
void stergere(int poz)
{
int val = introdus[poz];
int pozitie = Poz[val];
//cout << poz << " " << val << " " << pozitie << "\n";
swap(Poz[heap[pozitie]], Poz[heap[heap.size() - 1]]);
swap(heap[pozitie], heap[heap.size() - 1]);
heap.pop_back();
coboara(pozitie);
urca(pozitie);
}
int main()
{
in >> n;
introdus.push_back(0);
for(int i = 0; i < n; ++i)
{
in >> task;
if(task == 1 || task == 2) in >> x;
if(task == 1) inserare(x);
if(task == 2) stergere(x);
if(task == 3) out << heap[0] << "\n";
/*for(int i = 0; i < heap.size(); ++i) cout << heap[i] << " ";
cout << "\n";
for(int i = 0; i < introdus.size(); ++i) cout << introdus[i] << " ";
cout << "\n";*/
}
//for(int i = 0; i < heap.size(); ++i) cout << heap[i] << " ";
return 0;
}