Pagini recente » Cod sursa (job #2416319) | Cod sursa (job #1700193) | Cod sursa (job #416524) | Cod sursa (job #1870581) | Cod sursa (job #2207005)
#include <stdio.h>
#define nmax 200001
typedef struct {
int val;
int contor;
} heap;
heap v[nmax];
int poz_heap, co;
void urcare_heap( int poz ) {
heap aux;
while ( poz / 2 > 0 && v[ poz / 2 ].val > v[ poz ].val ) { ///interschimbam elementul cu tatal sau
aux = v[ poz / 2 ];
v[ poz / 2 ] = v[poz];
v[poz] = aux;
poz /= 2;
}
}
void coborare_heap( int poz ) {
heap aux;
while ( ( poz * 2 <= poz_heap && v[ poz * 2 ].val < v[poz].val ) || ( ( poz * 2 + 1 ) <= poz_heap && v[ poz * 2 + 1 ].val < v[poz].val ) ) {
if ( v[ poz * 2 ].val < v[poz].val ) {
aux = v[ poz * 2 ];
v[ poz * 2 ] = v[poz];
v[poz] = aux;
poz *= 2;
}
else if ( ( poz * 2 + 1 ) <= poz_heap && v[ poz * 2 + 1 ].val < v[poz].val ) {
aux = v[ poz * 2 + 1 ];
v[ poz * 2 + 1 ] = v[poz];
v[poz] = aux;
poz = poz * 2 + 1;
}
}
}
void inserare_heap( int nr ) {
poz_heap++;
v[poz_heap].val = nr; ///inseram nr pe ultima pozitie in heap
v[poz_heap].contor = ++co;
urcare_heap( poz_heap );
coborare_heap( poz_heap );
}
void stergere_heap( int ordin_insertie ) {
heap aux;
int i = 1;
while( i <= poz_heap && ordin_insertie != v[i].contor )
i++;
if ( i <= poz_heap ) {
aux = v[i];
v[i] = v[poz_heap];
v[poz_heap] = aux;
poz_heap--;
urcare_heap( poz_heap );
coborare_heap( poz_heap );
}
}
int main() {
int n, i, ver, nr;
FILE *fin, *fout;
fin = fopen( "heapuri.in", "r" );
fout = fopen( "heapuri.out", "w" );
fscanf( fin, "%d", &n );
for ( i = 0; i < n; i++ ) {
fscanf( fin, "%d", &ver );
if ( ver == 3 )
fprintf( fout, "%d\n", v[1].val );
else {
fscanf( fin, "%d", &nr );
if ( ver == 1 )
inserare_heap( nr );
else
stergere_heap( nr );
}
}
fclose( fin );
fclose( fout );
return 0;
}