Pagini recente » Cod sursa (job #1351415) | Cod sursa (job #2177052) | Cod sursa (job #2919970) | Cod sursa (job #3041319) | Cod sursa (job #2454487)
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int heap[200000];
int poz[200000];
int pozdepoz[200000];
int min( int a, int b ) {
if ( a < b )
return a;
return b;
}
void insert_heap( int x, int n, int cont ) {
heap[n] = x;
poz[n] = cont;
pozdepoz[poz[n]] = n;
n ++;
int i = n - 1;
while ( i > 0 && heap[i] < heap[( i - 1 ) / 2] ) {
swap( heap[i], heap[( i - 1 ) / 2] );
swap( poz[i], poz[( i - 1 ) / 2] );
pozdepoz[poz[i]] = i;
pozdepoz[poz[( i - 1 ) / 2 ]] = ( i - 1 ) / 2;
i = ( i - 1 ) / 2;
}
}
void remove_heap( int i, int n ) {
swap( heap[i], heap[n - 1] );
swap( poz[i], poz[n - 1] );
pozdepoz[poz[i]] = i;
pozdepoz[poz[n - 1]] = n - 1;
n --;
while ( i * 2 + 2 < n && heap[i] > min( heap[i * 2 + 1], heap[i * 2 + 2] ) ) {
if ( min( heap[i * 2 + 1], heap[i * 2 + 2] ) == heap[i * 2 + 1] ) {
swap( heap[i], heap[i * 2 + 1] );
swap( poz[i], poz[i * 2 + 1] );
pozdepoz[poz[i]] = i;
pozdepoz[poz[i * 2 + 1]] = i * 2 + 1;
i = i * 2 + 1;
} else {
swap( heap[i], heap[i * 2 + 2] );
swap( poz[i], poz[i * 2 + 2] );
pozdepoz[poz[i]] = i;
pozdepoz[poz[i * 2 + 2]] = i * 2 + 2;
i = i * 2 + 2;
}
}
i = 0;
if ( n > 1 && heap[i] > heap[i + 1] ) {
swap( heap[i], heap[i * 2 + 1] );
swap( poz[i], poz[i * 2 + 1] );
pozdepoz[poz[i]] = i;
pozdepoz[poz[i * 2 + 1]] = i * 2 + 1;
}
}
int main() {
FILE *fin = fopen( "heap.in", "r" ), *fout = fopen( "heap.out", "w" );
int i, a, n, x, cer, cont = 0, cnt = 0;
fscanf( fin, "%d", &x );
n = 0;
for ( i = 0; i < x; i ++ ) {
fscanf( fin, "%d", &cer );
switch( cer ) {
case 1:
fscanf( fin, "%d", &a );
insert_heap( a, n, cont );
n ++;
cont ++;
break;
case 2:
fscanf( fin, "%d", &a );
remove_heap( pozdepoz[a - 1], n );
n --;
break;
case 3:
fprintf( fout, "%d\n", heap[0] );
break;
}
}
fclose( fout );
fclose( fin );
return 0;
}