Pagini recente » Cod sursa (job #156537) | Cod sursa (job #1702687) | Cod sursa (job #1656965) | Cod sursa (job #81633) | Cod sursa (job #1738774)
#include <iostream>
#include <fstream>
using namespace std;
int heap[200010],n,pos[200010];
ifstream f("heapuri.in");
ofstream g("heapuri.out");
void Swap(int x,int y)
{
swap(heap[x],heap[y]);
swap(pos[x],pos[y]);
}
void check_sib(int i,int n)
{
if(i==1)
return;
if(i%2==1 && heap[i]<heap[i-1])
Swap(i,i-1);
if(i%2==0 && heap[i]>heap[i+1] && i+1<=n)
Swap(i,i+1);
}
void heap_insert(int &n,int x)
{
n++;
heap[n]=x;
pos[n]=n;
int i=n;
while(heap[i]<heap[i/2] && i/2>=1)
{
Swap(i,i/2);
check_sib(i,n);
i=i/2;
}
check_sib(i,n);
}
void heap_delete(int &n,int x)
{
int elem;
for(int i=1;i<n;i++)
{
if(pos[i]==x)
elem=i;
}
heap[elem]=heap[n];
pos[elem]=pos[n];
n--;
int i=elem;
while(heap[i]>heap[2*i] && 2*i<=n)
{
Swap(i,2*i);
check_sib(i,n);
i=2*i;
}
check_sib(i,n);
}
void printheap(int n)
{
for(int i=1;i<=n;i++)
cout << heap[i] << " ";
cout << "\n";
}
int main()
{
int n=0;
int m,x,a;
f>>m;
for(int i=0;i<m;i++)
{
f>>a;
if(a==1)
{
f>>x;
heap_insert(n,x);
}
if(a==2)
{
f>>x;
heap_delete(n,x);
}
if(a==3)
g << heap[1] << "\n";
}
return 0;
}