Pagini recente » Cod sursa (job #1719798) | Cod sursa (job #273367) | Cod sursa (job #2930812) | Cod sursa (job #2674037) | Cod sursa (job #596978)
Cod sursa(job #596978)
const f = 'apm.in'; g = 'apm.out';
type muchie = record
x, y, cost : longint;
end;
type vector = array[0..400001] of muchie;
var
MC : vector;
aux : muchie;
n, m, i, j : longint;
sf : longint;
TREE : array[0..200001] of longint;
APM : array[0..200001] of muchie;
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 grupa( i : longint ) : longint;
begin
if Tree[i] = i then Tree[i] := i
else Tree[i] := grupa(Tree[i]);
grupa := Tree[i];
end;
procedure kruskal();
var
x, y, i, costmin : longint;
begin
quick(MC, 1, m );
costmin := 0;
for i := 1 to n do TREE[i] := i;
j := 1;
x := MC[j].x; y := MC[j].y;
for i := 1 to n-1 do begin
while grupa(x) = grupa(y) do begin
inc( j );
x := MC[j].x;
y := MC[j].y;
end;
Tree[grupa(x)] := grupa(y);
costmin := costmin + MC[j].cost;
APM[i] := MC[j];
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( n-1 );
for i := 1 to n-1 do writeln( APM[i].x,' ',APM[i].y );
end.