Pagini recente » Cod sursa (job #1818313) | Cod sursa (job #344268) | Clasament preONI 2006, Clasele XI-XII | Cod sursa (job #669041) | Cod sursa (job #979011)
Cod sursa(job #979011)
#include <iostream>
#include <fstream>
using namespace std;
#define Nmax 200004
#define Parent(i) i/2
#define LeftSon(i) 2*i
#define RightSon(i) 2*i+1
int H[Nmax]; // h
int poz[Nmax]; //poz
int order[Nmax]; //ind
int N, M, ord;
void swapp( int a, int b )
{
swap( order[a], order[b] );
poz[ order[a] ] = a;
poz[ order[b] ] = b;
swap( H[a], H[b] );
}
void DownHeap( int poz1 )
{
int k = poz1;
int j;
do
{
j = k;
if ( LeftSon(j) <= N && H[LeftSon(j)] < H[k] ) k = LeftSon(j);
if ( RightSon(j) <= N && H[RightSon(j)] < H[k] ) k = RightSon(j);
swapp( j, k );
} while( j != k );
}
void UpHeap( int poz1 )
{
int k = poz1;
int j;
do
{
j = k;
if ( j > 1 && H[Parent(j)] > H[k] ) k = Parent(j);
swapp( j, k );
} while( j != k );
}
void InsertHeap( int key )
{
H[ ++N ] = key;
poz[ ++ord ] = N;
order[N] = ord;
UpHeap( N );
}
void DeleteHeap( int key )
{
int pz = poz[key];
swap( order[pz], order[N] );
poz[ order[pz] ] = pz;
poz[ order[N] ] = N;
swap( H[pz], H[N] );
N--;
UpHeap( pz );
DownHeap( pz );
}
int main()
{
ifstream f("heapuri.in");
ofstream g("heapuri.out");
f >> M;
for ( int tip, key, i = 1; i <= M; i++ )
{
f >> tip;
switch( tip )
{
case 1:
f >> key;
InsertHeap(key);
break;
case 2:
f >> key;
DeleteHeap(key);
break;
case 3:
g << H[1] << "\n";
break;
default: break;
}
}
return 0;
}