Pagini recente » Cod sursa (job #1545758) | Cod sursa (job #1921561) | Cod sursa (job #2959182) | Cod sursa (job #1943283) | Cod sursa (job #696465)
Cod sursa(job #696465)
#include <fstream>
#define fs(x) x*2
#define fd(x) x*2+1
#define t(x) x/2
using namespace std;
int val[200010],h[200010],l[200010],n,m,nr;
int maxx(int a,int b)
{
if(val[a]>val[b])
return a;
return b;
}
void sift(int i)
{
do
{
if(fs(i)<=m&&val[h[fs(i)]]<val[h[i]])
{
if(fd(i)<=m&&val[h[fd(i)]]<val[h[i]])
{
int s=maxx(fs(i),fd(i));
swap(h[s],h[i]);
swap(l[h[s]],l[h[i]]);
i=s;
}
else
{
swap(h[fs(i)],h[i]);
swap(l[h[fs(i)]],l[h[i]]);
i=fs(i);
}
}
else
if(fd(i)<=m&&val[h[fd(i)]]<val[h[i]])
{
swap(h[fd(i)],h[i]);
swap(l[h[fd(i)]],l[h[i]]);
i=fd(i);
}
else return ;
} while (1);
}
void percolate(int i)
{
do
{
if(val[h[i]]<val[h[t(i)]])
{
swap(h[i],h[t(i)]);
swap(l[h[i]],l[h[t(i)]]);
i=t(i);
}
else
return;
} while (1);
}
void insert(int x)
{
val[++nr]=x;
h[++m]=nr;l[nr]=m;
if(val[h[m/2]]>val[h[m]])
{
swap(h[m/2],h[m]);
swap(l[h[m/2]],l[h[m]]);
percolate(m/2);
}
}
void delet(int x)
{
int i=l[x];
h[i]=h[m];h[m--]=0;
if(i!=m+1)
if(val[h[i]]<val[h[t(i)]])
percolate(i);
else
sift(i);
}
int main()
{
ifstream f("heapuri.in");
f>>n;
int o;
ofstream g("heapuri.out");
for(int i=0;i<n;i++)
{
f>>o;int x;
switch(o)
{
case 1: f>>x; insert(x);break;
case 2: f>>x; delet(x);break;
case 3: g<<val[h[1]]<<'\n';
}
}
return 0;
}