Pagini recente » Cod sursa (job #1499695) | Cod sursa (job #3229236) | Cod sursa (job #2102608) | Cod sursa (job #2420197) | Cod sursa (job #1466136)
#include<iostream>
#include<fstream>
using namespace std;
int heap[200001], cnt = 1;
int el[200001], cntEl = 1;
int poz[200001];
void percolate(int n)
{
while((n != 1) && (heap[n] < heap[n/2]))
{
int aux = heap[n/2];
poz[heap[n]] = n/2;
poz[heap[n/2]] = n;
heap[n/2] = heap[n];
heap[n] = aux;
n = n/2;
}
}
void sift(int n)
{
int max, aux=0;
#ifdef DEBUG
cout<<"sift()"<<endl;
#endif
if( (2*n < cnt) && heap[2*n]<heap[n])
aux = 2*n;
if( (2*n +1 < cnt) && heap[2*n+1]<heap[n])
if(heap[2*n+1] < heap[2*n])
aux = 2*n+1;
while(aux!=0)
{
#ifdef DEBUG
cout<<"Schimb "<< aux<<" cu "<<n<<endl;
#endif
int change = heap[n];
poz[heap[aux]] = n;
poz[change] = aux;
heap[n] = heap[aux];
heap[aux] = change;
n = aux;
aux = 0;
if( (2*n < cnt) && heap[2*n]<heap[n])
aux = 2*n;
if( (2*n +1 < cnt) && heap[2*n+1]<heap[n])
if(heap[2*n+1] < heap[2*n])
aux = 2*n+1;
}
}
void list()
{
for(int i=0;i<cnt;i++)
cout<<heap[i]<<" ";
cout<<endl;
}
int main()
{
fstream fin;
fin.open("heapuri.in");
ofstream fout;
fout.open("heapuri.out");
int N;
fin>>N;
for(int i=0;i<N;i++)
{
int a,b;
fin>>a;
if(a==1)
{
fin>>b;
#ifdef DEBUG
cout<<"Adaug "<<b<<" pe pozitia "<<cnt<<endl;
#endif
heap[cnt++] = b;
poz[b] = cnt-1;
el[cntEl++] = b;
percolate(cnt-1);
#ifdef DEBUG
list();
#endif
} else if(a==2)
{
fin>>b;
#ifdef DEBUG
cout<<"Stergem pe "<< el[b]<<" aflat pe pozitia "<<poz[el[b]] <<endl;
cout<<"b="<<b<<endl;
#endif
b = el[b];
poz[heap[cnt-1]] = poz[b];
heap[poz[b]] = heap[cnt-1];
cnt--;
if((poz[b]/2 >=1) && heap[poz[b]] < heap[poz[b/2]])
{
percolate(poz[b]);
}
else
{
sift(poz[b]);
}
#ifdef DEBUG
list();
#endif
} else if(a==3)
{
fout<<heap[1]<<endl;
}
}
#ifdef DEBUG
list();
#endif
fin.close();
fout.close();
return 0;
}