Pagini recente » Cod sursa (job #1241069) | Cod sursa (job #2361799) | Cod sursa (job #1828648) | Cod sursa (job #490397) | Cod sursa (job #2024926)
#include<stdio.h>
#include<utility>
#define MAXN 200000
void add(int x,int i);
void rmv(int nod);
void sift(int nod);
void percolate(int nod);
int left_son(int nod);
int right_son(int nod);
int father(int nod);
void swap_nodes(int nod1,int nod2);
FILE*fin,*fout;
std::pair<int,int> heap[MAXN+1];
int poz[MAXN+1];
int N=0;
int main()
{
fin=fopen("heapuri.in","r");
fout=fopen("heapuri.out","w");
int nr_op;
fscanf(fin,"%d",&nr_op);
int cron=0;
for(int i=1;i<=nr_op;i++)
{
int op;
fscanf(fin,"%d",&op);
if(op==1)
{
int x;
fscanf(fin,"%d",&x);
add(x,++cron);
}
if(op==2)
{
int pos;
fscanf(fin,"%d",&pos);
rmv(poz[pos]);
}
if(op==3)
{
fprintf(fout,"%d\n",heap[1].first);
}
}
fclose(fin);
fclose(fout);
}
int left_son(int nod)
{
return nod*2;
}
int right_son(int nod)
{
return nod*2+1;
}
int father(int nod)
{
return nod/2;
}
void swap_nodes(int nod1,int nod2)
{
std::swap(heap[nod1].first,heap[nod2].first);
std::swap(heap[nod1].second,heap[nod2].second);
std::swap(poz[heap[nod1].second],poz[heap[nod2].second]);
}
void add(int x,int i)
{
heap[++N].first=x;
heap[N].second=i;
poz[i]=N;
percolate(N);
}
void rmv(int nod)
{
swap_nodes(nod,N);
N--;
if(nod > 1 && heap[nod].first < heap[father(nod)].first)
{
percolate(nod);
}
else
{
sift(nod);
}
}
void sift(int nod)
{
int son;
do
{
son=0;
if(right_son(nod) <=N)
{
if(heap[left_son(nod)].first < heap[right_son(nod)].first)
{
son=left_son(nod);
}
else
{
son=right_son(nod);
}
}
else if(left_son(nod)<=N)
{
son=left_son(nod);
}
if(heap[son].first > heap[nod].first)
{
son=0;
}
if(son)
{
swap_nodes(nod,son);
nod=son;
}
}while(son);
}
void percolate(int nod)
{
while(nod>1 && heap[nod].first < heap[father(nod)].first)
{
swap_nodes(nod,father(nod));
nod=father(nod);
}
}