标签:
1 const maxn=1050;maxm=100050; 2 type 3 edge=record 4 f,g,w:longint; 5 end; 6 var 7 i,j,k,l,m,n,tot:longint; 8 c:array[0..maxn] of longint; 9 a:array[0..maxm] of edge; 10 function getfat(x:longint):longint; 11 begin 12 if c[x]<>x then c[x]:=getfat(c[x]); 13 exit(c[x]); 14 end; 15 operator <(e1,e2:edge)x:boolean; //为了便于排序,重载运算符 16 begin 17 x:=e1.w<e2.w; 18 end; 19 operator >(e1,e2:edge)x:boolean; 20 begin 21 x:=e1.w>e2.w; 22 end; 23 procedure swap(var e1,e2:edge); 24 var e3:edge; 25 begin 26 e3:=e1;e1:=e2;e2:=e3; 27 end; 28 procedure sort(l,r:longint); 29 var 30 i,j:longint; 31 x:edge; 32 begin 33 i:=l;j:=r;x:=a[(l+r) div 2]; 34 repeat 35 while a[i]<x do inc(i); 36 while x<a[j] do dec(j); 37 if i<=j then 38 begin 39 swap(a[i],a[j]); 40 inc(i);dec(j); 41 end; 42 until i>j; 43 if l<j then sort(l,j); 44 if i<r then sort(i,r); 45 end; 46 function newedge(x,y,z:longint):edge; 47 var e1:edge; 48 begin 49 e1.f:=x;e1.g:=y;e1.w:=z; 50 exit(e1); 51 end; 52 begin 53 readln(n,m); 54 for i:=1 to n do c[i]:=i; 55 for i:=1 to m do 56 begin 57 readln(j,k,l); 58 a[i]:=newedge(j,k,l); 59 end; 60 sort(1,m); 61 j:=1;tot:=0; 62 for i:=1 to n-1 do 63 begin 64 repeat 65 k:=getfat(a[j].f); //并查集判定 66 l:=getfat(a[j].g); 67 if k<>l then break; 68 inc(j); 69 until j>m; 70 if j>m then break; //无法连通 71 c[k]:=l;tot:=tot+a[j].w; 72 end; 73 if j>m then writeln(-1) else writeln(tot); 74 end.
标签:
原文地址:http://www.cnblogs.com/Fefnir/p/5593613.html