Cod sursa(job #596868)

Utilizator vendettaSalajan Razvan vendetta Data 20 iunie 2011 09:15:59
Problema Arbore partial de cost minim Scor 0
Compilator fpc Status done
Runda Arhiva educationala Marime 2.47 kb
const f = 'apm.in'; g = 'apm.out';

type muchie = record
        x, y, cost : longint;
end;

type solutii = record
        x, y : longint;
end;

type vector= array[0..400067] of muchie;

var

    MC : vector;
    aux : muchie;
    n, m, i, j : longint;
    sf : longint;
    TREE, rang : array[0..200067] of longint;
    APM : array[0..400067] of solutii;
    buf, buf1 : array[1..1 shl 17 ] of char;

procedure quick( var a : vector; st: longint; dr : longint);
    var
        min, max, mij : longint;
    begin
        min := st;
        max := dr;
        mij := a[(st + dr) div 2].cost;
        repeat
            while (a[min].cost < mij) do inc( min );
            while (a[max].cost > mij) do dec( max );
            if (min <= max) then begin
                aux := a[min];
                a[min] := a[max];
                a[max] := aux;
                inc( min );
                dec( max );
            end;
        until (min >= max);
        if (st <= max) then quick(a, st, max);
        if (min <= dr) then quick(a, min, dr);
    end;

function multime( r : longint ) : longint;
    begin
        if (TREE[r]<>r) then TREE[r] := multime(Tree[r]);
        multime := r;
    end;

procedure reuneste(i, j : longint );
    var
        x, y, k : longint;

    begin
        x := TREE[i];
        y := TREE[j];
        if (x <> y) then begin
        if (rang[x] < rang[y]) then
             Tree[x] := y
        else Tree[y] := x;
        if (rang[x] = rang[y]) then inc( rang[x] );
        end;
    end;

procedure kruskal();
    var
        x, y, i, costmin : longint;
    begin

        quick(MC, 1, m );

        costmin := 0;
        for i := 1 to n do begin rang[i] := 0; TREE[i] := i; end;

        for i := 1 to m do begin
            x := MC[i].x;
            y := MC[i].y;
            if (TREE[x] <> TREE[y]) then begin
                reuneste( x, y );
                costmin := costmin + MC[i].cost;
                inc( sf );
                APM[sf].x := x;
                APM[sf].y := y;
            end;
        end;

        writeln( costmin );

    end;

begin
    assign( input,f ); reset( input );
    assign( output,g ); rewrite( output );
    settextbuf( input,buf );
    settextbuf( output,buf1 );
    readln( n, m );

    for i := 1 to m do
        readln(MC[i].x, MC[i].y, MC[i].cost);

    kruskal();

    writeln( sf );
    for i := 1 to sf do writeln( APM[i].x,' ',APM[i].y );
end.