Pagini recente » Cod sursa (job #985883) | Cod sursa (job #2365628) | Cod sursa (job #2242756) | Cod sursa (job #989318) | Cod sursa (job #979005)
Cod sursa(job #979005)
#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]; // v
int poz[Nmax]; //poz
int order[Nmax]; //h
int N, M, ord;
void DownHeap( int poz1 )
{
int k = poz1;
int j;
do
{
j = k;
if ( LeftSon(j) <= N && H[ order[LeftSon(j)] ] < H[ order[k] ] ) k = LeftSon(j);
if ( RightSon(j) <= N && H[ order[RightSon(j)] ] < H[ order[k] ] ) k = RightSon(j);
if ( j != k )
{
poz[ order[j] ] = k;
poz[ order[k] ] = j;
swap( order[j], order[k] );
}
} while( j != k );
}
void UpHeap( int poz1 )
{
int k = poz1;
int j;
do
{
j = k;
if ( j > 1 && H[ order[Parent(j)] ] > H[ order[k] ] ) k = Parent(j);
if ( H[ order[k] ] > H[ order[j] ] )
{
poz[ order[j] ] = k;
poz[ order[k] ] = j;
swap( order[j], order[k] );
}
} while( j != k );
}
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;
H[ ++N ] = key;
order[ ++ord ] = N;
poz[N] = ord;
UpHeap( ord );
break;
case 2:
f >> key;
ord--;
order[ poz[key] ] = order[ ord ];
poz[ order[ord] ] = poz[key];
//UpHeap(poz[key]);
DownHeap(poz[key]);
break;
case 3:
g << H[ order[1] ] << "\n";
break;
default: break;
}
}
return 0;
}