Pagini recente » Cod sursa (job #3171441) | Cod sursa (job #2906939) | Cod sursa (job #2808321) | Cod sursa (job #1056400) | Cod sursa (job #504995)
Cod sursa(job #504995)
#include <cstdio>
#include <fstream>
#define nmax 200010
using namespace std;
FILE *fin=fopen("heapuri.in", "r");
FILE *fout=fopen("heapuri.out", "w");
int poz[nmax], a[nmax], h[nmax];
int n, m, nr;
void heapUp(int k);
void heapDown(int k);
void insert_(int k);
void delete_(int k);
int right_son(int k)
{
return 2*k+1;
}
int left_son(int k)
{
return 2*k;
}
int father(int k)
{
return k/2;
}
void heapUp(int k)
{
int aux;
while(k>1 && h[k]<h[k/2])
{
aux = h[k];
h[k] = h[k/2];
h[k/2] = aux;
aux = a[k];
a[k] = a[k/2];
a[k/2] = aux;
poz[a[k]] = k;
poz[a[k/2]] = k/2;
k/=2;
}
}
void heapDown(int x)
{
int son, aux;
do
{
son = 0;
if(left_son(x) <= n)
son = left_son(x);
if(right_son(x) <=n && right_son(x) > left_son(x))
son = right_son(x);
if(h[x] <= h[son])
son = 0;
if(son)
{
aux = h[x];
h[x] = h[son];
h[son] = aux;
aux = a[x];
a[x] = a[son];
a[son] = aux;
poz[a[x]] = x;
poz[a[son]] = son;
}
} while(son);
}
void insert_(int x)
{
++n; ++nr;
h[n] = x; //heapul
a[n] = nr; //al cata-lea e inserat
poz[nr] = n; //pozitia celui de-al nr inserat
heapUp(n);
}
void delete_(int x)
{
int k = poz[x];
h[k] = h[n];
--n;
if(h[k]<h[k/2])
heapUp(k);
else
heapDown(k);
}
int main()
{
int i, j, cod, x;
fscanf(fin, "%d", &m);
for(i=1;i<=m;++i)
{
fscanf(fin, "%d", &cod);
if(cod < 3)
fscanf(fin, "%d", &x);
if(cod == 1)
insert_(x);
if(cod == 2)
delete_(x);
if(cod == 3)
{
//for(j=1;j<=n;++j)
//fprintf(fout, "%d ", h[j]);
//fprintf(fout, "\n");
fprintf(fout, "%d\n", h[1]);
}
}
return 0;
}