Pagini recente » Cod sursa (job #703238) | Cod sursa (job #671840) | Cod sursa (job #190540) | Cod sursa (job #752486) | Cod sursa (job #1946046)
#include <iostream>
#include <cstdio>
#include <unordered_map>
#define MAXN 200005
#define INFINIT 0x3f3f3f3f
using namespace std;
int q, n, k;
int heap[MAXN];
int ins[MAXN];
unordered_map<int,int> pos;
void heap_update(int n)
{
if(heap[n/2] > heap[n])
{
pos[heap[n/2]] = n;
pos[heap[n]] = n/2;
swap(heap[n/2],heap[n]);
heap_update(n/2);
}
}
void heap_insert(int x)
{
++n;
heap[n]=x;
pos[x] = n;
heap_update(n);
}
void heap_resolve(int nod)
{
if((2*nod <=n && heap[nod] <= heap[2*nod]) \
&& (2*nod+1 <= n && heap[nod] <= heap[2*nod+1]))
return;
int left = INFINIT, right = INFINIT;
if(2*nod <= n)
{
left = heap[2*nod];
}
if(2*nod +1 <= n)
{
right = heap[2*nod + 1];
}
if(left == right)
return;
if(left < right && heap[2*nod] < heap[nod] && 2*nod <=n)
{
pos[heap[nod]] = 2 * nod;
pos[heap[2*nod]] = nod;
swap(heap[nod],heap[2*nod]);
heap_resolve(2*nod);
}
else if(heap[2*nod+1] < heap[nod] && 2*nod +1 <=n)
{
pos[heap[nod]] = 2 * nod + 1;
pos[heap[2*nod + 1]] = nod;
swap(heap[nod],heap[2*nod+1]);
heap_resolve(2*nod+1);
}
}
void heap_remove(int nod)
{
swap(heap[nod],heap[n]);
pos[heap[nod]] = n;
pos[heap[n]] = nod;
--n;
heap_resolve(nod);
}
class InParser
{
char *b;
int bi, bs;
FILE *in;
inline bool isdigit(char c)
{
return c>='0' && c<='9';
}
public:
InParser(const char *s)
{
in = fopen(s,"r");
fseek(in,0,SEEK_END);
bs = ftell(in);
b = new char[bs+1];
fseek(in,0,SEEK_SET);
fread(b,1,bs,in);
bi = 0;
}
InParser& operator>>(int &x)
{
x = 0;
while(!isdigit(b[bi]))
bi++;
while(isdigit(b[bi]))
{
x = x * 10 + b[bi] - '0';
++bi;
}
return *this;
}
};
int main()
{
InParser in("heapuri.in");
freopen("heapuri.out","w",stdout);
in>>q;
while(q--)
{
int op;
in>>op;
if(op==1)
{
int x;
in>>x;
heap_insert(x);
ins[++k] = x;
}
else if(op==3)
{
printf("%d\n",heap[1]);
}
else if(op==2)
{
int x;
in>>x;
int pos_heap = pos[ins[x]];
heap_remove(pos_heap);
}
}
return 0;
}