Pagini recente » Cod sursa (job #2433168) | Cod sursa (job #720567) | Cod sursa (job #1040538) | Cod sursa (job #111063) | Cod sursa (job #596787)
Cod sursa(job #596787)
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..400001] of muchie;
var
MC : vector; // vector de tip graf(retin muchia + costul ei)
aux : muchie;
n, m, i, j : longint;
sf : longint; // nr-ul muchiilor din APM;
TREE : array[0..200000] of longint; //vectorul de arbori disjuncti
APM : array[0..400001] of solutii; // arborele partial minim
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;
procedure reuneste(i, j : longint );
var
x, y, k : longint;
begin
x := TREE[i];
y := TREE[j];
if (x <> y) then // daca vf i din al x-lea arbore e diferit de vf j din al y-lea arbore
for k := 1 to n do // pt fiecare arbore
if TREE[k]=x then TREE[k] := y; //unesc arborii disjuncti
end;
procedure kruskal();
var
x, y, i, costmin : longint;
begin
quick(MC, 1, m ); //sortez crescator muchiile in fct de cost
costmin := 0; // init costmin cu 0;
for i := 1 to n do TREE[i] := i; // init vectorul de arbori
for i := 1 to m do begin // pt fiecare muchie
x := MC[i].x;
y := MC[i].y;
if (TREE[x] <> TREE[y]) then begin // daca vf x din al TREE[x]-lea arbore e diferit de vf y din al TREE[y]-lea arbore
reuneste( x, y ); //unesc arborii disjuncti
costmin := costmin + MC[i].cost; // adaug costul muchiei la costul total
inc( sf ); // incrementez nr-ul muchiilor din APM
APM[sf].x := x; // adaug solutiile
APM[sf].y := y; // adaug solutiile
end;
end;
writeln( costmin ); // afisez costul minim
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.