Pagini recente » Cod sursa (job #1826333) | Cod sursa (job #1573290) | Cod sursa (job #438439) | Cod sursa (job #2282191) | Cod sursa (job #2815183)
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
vector <int> heap(1, 0), poz(1, 0), v(1, 0);
int k, len;
const int NMAX = 200005;
bool empty()
{
return (heap.size() == 1);
}
void insert(int x)
{
int pos = len + 1;
heap.push_back(++k);
len++;
v.push_back(x);
poz.push_back(k);
while(pos / 2 >= 1)
{
if(v[heap[pos]] < v[heap[pos / 2]])
{
swap(poz[heap[pos]], poz[heap[pos / 2]]);
swap(heap[pos], heap[pos / 2]);
}
else
break;
pos = pos / 2;
}
}
void pop(int x)
{
int pos = poz[x], ok = 1, aux;
aux = heap[len];
swap(heap[poz[x]], heap[len]);
swap(poz[x], poz[aux]);
len--;
aux = pos;
while(pos / 2 >= 1)
{
if(v[heap[pos]] < v[heap[pos / 2]])
{
swap(poz[heap[pos]], poz[heap[pos / 2]]);
swap(heap[pos], heap[pos / 2]);
ok = 0;
}
else
break;
pos = pos / 2;
}
pos = aux;
if(ok)
{
int pos_min;
while(pos * 2 <= len)
{
pos_min = -1;
if(v[heap[pos]] > v[heap[pos * 2]])
pos_min = pos * 2;
if(pos * 2 + 1 <= len && v[heap[pos]] > v[heap[pos * 2 + 1]] && v[heap[pos * 2 + 1]] < v[heap[pos * 2]])
pos_min = pos * 2 + 1;
if(pos_min == -1)
break;
swap(poz[heap[pos]], poz[heap[pos_min]]);
swap(heap[pos], heap[pos_min]);
pos = pos_min;
}
}
}
int top()
{
return v[heap[1]];
}
int main()
{
int m, i, op, x;
fin >> m;
while(m--)
{
fin >> op;
if(op == 1)
{
fin >> x;
insert(x);
}
else if(op == 2)
{
fin >> x;
pop(x);
}
else
{
fout << top() << '\n';
}
}
return 0;
}