Virtual Object
::
Programs
:: Остовное дерево минимального веса |
||||
Наша кнопка |
||||
Остовное дерево минимального веса {$APPTYPE CONSOLE} type ostov=record first,second,weight:longint; end; var p,r:array [1..1000] of longint; a:array [1..1000] of ostov; n,m,i,res:longint; ⁄⁄----------------------------------------------- procedure swap(var x,y:longint); var temp:longint; begin temp:=x; x:=y; y:=temp; end; ⁄⁄----------------------------------------------- procedure qsort(l,r:longint); var i,j,x:longint; begin x:=a[l+random(r-l+1)].weight; i:=l; j:=r; repeat while a[i].weight < x do inc(i); while a[j].weight > x do dec(j); if i<=j then begin swap(a[i].weight,a[j].weight); swap(a[i].first,a[j].first); swap(a[i].second,a[j].second); inc(i); dec(j); end; until i>j; if l<j then qsort(l,j); if i<r then qsort(i,r); end; ⁄⁄----------------------------------------------- procedure make_set(x:longint); begin p[x]:=x; r[x]:=0; end; ⁄⁄----------------------------------------------- function find_set(x:longint):longint; begin if p[x]=x then find_set:=x else begin p[x]:=find_set(p[x]); find_set:=p[x]; end; end; ⁄⁄----------------------------------------------- procedure link_set(x,y:longint); begin if r[x]>r[y] then p[y]:=x else begin p[x]:=y; if r[x]=r[y] then inc(r[y]); end; end; ⁄⁄----------------------------------------------- procedure union_set(x,y:longint); begin link_set(find_set(x),find_set(y)); end; ⁄⁄----------------------------------------------- procedure span; var i:longint; begin qsort(1,m); for i:=1 to n do make_set(i); for i:=1 to m do if find_set(a[i].first) <> find_set(a[i].second) then begin inc(res,a[i].weight); writeln(a[i].first,′ ′,a[i].second); union_set(a[i].first,a[i].second); end; end; ⁄⁄----------------------------------------------- begin assign(input,′input.txt′);reset(input); assign(output,′output.txt′);rewrite(output); readln(n,m); res:=0; for i:=1 to m do readln(a[i].first,a[i].second,a[i].weight); span; write(res); close(input); close(output); end. |
||||
Object © 2004 - 2005. All rights reserved. |