[复习]最小生成树 最优布线问题

来源:互联网 发布:王德民 知乎 编辑:程序博客网 时间:2024/05/17 02:59

题目描述
学校有 n 台计算机,为了方便数据传输,现要将它们用数据线连接起来。两台计算机被连接是指它们间有数据线连接。由于计算机所处的位置不同,因此不同的两台计算机的连接费用往往是不同的。

当然,如果将任意两台计算机都用数据线连接,费用将是相当庞大的。为了节省费用,我们采用数据的间接传输手段,即一台计算机可以间接的通过若干台计算机(作为中转)来实现与另一台计算机的连接。

现在由你负责连接这些计算机,任务是使任意两台计算机都连通(不管是直接的或间接的)。

输入格式
输入文件第一行为整数 n(2<=n<=100),表示计算机的数目。此后的 n 行,每行 n 个整数。第 x+1 行 y 列的整数表示直接连接第 x 台计算机和第 y 台计算机的费用。

输出格式
输出文件是一个整数,表示最小的连接费用。

样例数据
输入

3
0 1 2
1 0 1
2 1 0

输出

2

备注
【样例说明】
表示连接 1和2, 2和3,费用为2 。

分析:最小生成树模板

代码

#include<iostream>#include<cstdio>#include<cstdlib>#include<cstring>#include<string>#include<ctime>#include<cmath>#include<algorithm>#include<cctype>#include<iomanip>#include<queue>#include<set>using namespace std;int getint(){    int sum=0,f=1;    char ch;    for(ch=getchar();!isdigit(ch)&&ch!='-';ch=getchar());    if(ch=='-')    {        f=-1;        ch=getchar();    }    for(;isdigit(ch);ch=getchar())        sum=(sum<<3)+(sum<<1)+ch-48;    return sum*f;}struct node{    int fro,to,w;}bian[10010];int n,cost,x,y,cnt,ans,fa[10010];bool comp(const node &a,const node &b){    return a.w<b.w;}int getfa(int x){    if(x==fa[x])        return x;    fa[x]=getfa(fa[x]);    return fa[x]; }int main(){    freopen("computer.in","r",stdin);    freopen("computer.out","w",stdout);    n=getint();    for(int i=1;i<=n;++i)        for(int j=1;j<=n;++j)        {            cost=getint();            if(j>i)                bian[++cnt].fro=i,bian[cnt].to=j,bian[cnt].w=cost;        }    sort(bian+1,bian+cnt+1,comp);    for(int i=1;i<=n;++i)        fa[i]=i;    for(int i=1;i<=cnt;++i)    {        x=getfa(bian[i].fro),y=getfa(bian[i].to);        if(x!=y)        {            fa[x]=y;            ans+=bian[i].w;        }    }    cout<<ans<<'\n';    return 0;}

本题结。

原创粉丝点击