最小生成树II

来源:互联网 发布:Ubuntu 12 开机启动 编辑:程序博客网 时间:2024/06/13 07:23

Description

  农民约翰被选为他们镇的镇长!他其中一个竞选承诺就是在镇上建立起互联网,并连接到所有的农场。当然,他需要你的帮助。约翰已经给他的农场安排了一条高速的网络线路,他想把这条线路共享给其他农场。为了用最小的消费,他想铺设最短的光纤去连接所有的农场。你将得到一份各农场之间连接费用的列表,你必须找出能连接所有农场并所用光纤最短的方案。每两个农场间的距离不会超过100000

Input

第一行: 农场的个数,N(3<=N<=5000)。
第二行..结尾: 后来的行包含了一个N*N的矩阵,表示每个农场之间的距离。理论上,他们是N行,每行由N个用空格分隔的数组成,实际上,他们限制在80个字符,因此,某些行会紧接着另一些行。当然,对角线将会是0,因为不会有线路从第i个农场到它本身。

Output

只有一个输出,其中包含连接到每个农场的光纤的最小长度。

Sample Input

4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0

Sample Output

28

分析
先排序,再用并查集做。

程序:

varf,a,b:array[0..25000000]of longint;re:array[0..5010]of longint;n,p,i,j,ans,m,check,k,l:longint;procedure kp(l,r:longint);vari,j,mid,t:longint;begin    if l>r then exit;    i:=l;j:=r;mid:=f[(l+r) div 2];    repeat         while f[i]<mid do inc(i);         while f[j]>mid do dec(j);         if i<=j then         begin             t:=f[i];f[i]:=f[j];f[j]:=t;             t:=a[i];a[i]:=a[j];a[j]:=t;             t:=b[i];b[i]:=b[j];b[j]:=t;             inc(i);dec(j);         end;    until(i>j);    kp(l,j);    kp(i,r);end;function find(x:longint):longint;vark,temp:longint;begin    k:=x;    while re[x]<>x do x:=re[x];    while re[k]<>x do    begin        temp:=re[k];        re[k]:=x;        k:=temp;    end;    exit(x);end;begin    readln(n);    p:=0;    for i:=1 to n do    begin        for j:=1 to n do        begin            inc(p);            read(f[p]);            a[p]:=i;            b[p]:=j;        end;        readln;    end;    kp(1,p);    ans:=0;    for i:=1 to n do    re[i]:=i;    for i:=1 to p do    begin        m:=re[1];        check:=0;        for j:=1 to n do        if re[j]<>m then check:=1;        if check=0 then        begin            write(ans);            break;        end;        if find(a[i])<>find(b[i]) then        begin            k:=find(re[b[i]]);            l:=re[a[i]];            re[k]:=l;            ans:=ans+f[i];        end;    end;end.