Cod sursa(job #599521)

Utilizator Luncasu_VictorVictor Luncasu Luncasu_Victor Data 28 iunie 2011 23:44:06
Problema Heapuri Scor 100
Compilator fpc Status done
Runda Arhiva educationala Marime 1.97 kb
const   fin = 'heapuri.in'; fout = 'heapuri.out';

type
        heap = array[1..200 * 1000] of longword;
var
        h, a, pos : heap;

procedure swap( var a , b : longword );
var
        c : longword;
begin
        c := a; a := b; b := c;
end;

procedure insert(var n ,r : longword; x : longword);
var
        t, f : longword;
begin
        r := r + 1;
        n := n + 1;
        h[n] := x;
        a[n] := r;
        pos[r] := n;
        f := n;
        t := f div 2;
        while (t > 0) and (h[t] > h[f]) do
        begin
                swap( h[t] , h[f] );
                pos[a[t]] := f;
                pos[a[f]] := t;
                swap( a[t] , a[f] );
                f := t;
                t := f div 2;
        end;
end;

procedure delete(var n : longword; r : longword);
var
        t ,f : longword;
begin
        h[pos[r]] := h[n];
        a[pos[r]] := a[n];
        pos[a[n]] := pos[r];
        t := pos[r];
        f := 2 * t;
        if (f + 1 <= n) and (h[f + 1] < h[f]) then f := f + 1;
        while (f <= n) and (h[f] < h[t]) do
        begin
                swap( h[t], h[f] );
                pos[a[t]] := f;
                pos[a[f]] := t;
                swap( a[t], a[f] );
                t := f;
                f := 2 * t;
                if (f + 1 <= n) and (h[f + 1] < h[f]) then f := f + 1;
        end;
end;

procedure main();
var
        n, i, x, r, m : longword;
        op : byte;
begin
        assign( input, fin ); reset( input );
        assign( output, fout ); rewrite( output );

        n := 0;
        r := 0;
        readln( m );
        for i := 1 to m do
        begin
                read( op );
                if (op = 3) then write( h[1], #10 ) else
                begin
                        read( x );
                        if (op = 1) then insert( n, r, x ) else
                        delete( n, x );
                end;
        end;
end;

begin
        main();
end.