codevs 2627 村村通

题目描述 Description
农民约翰被选为他们镇的镇长!他其中一个竞选承诺就是在镇上建立起互联网,并连接到所有的农场。当然,他需要你的帮助。

约翰已经给他的农场安排了一条高速的网络线路,他想把这条线路共享给其他农场。为了用最小的消费,他想铺设最短的光纤去连接所有的农场。

你将得到一份各农场之间连接费用的列表,你必须找出能连接所有农场并所用光纤最短的方案。每两个农场间的距离不会超过100000

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

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

样例输入 Sample Input
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0

样例输出 Sample Output
28

数据范围及提示 Data Size & Hint
暂时无范围。

//求最小生成树的长度 
#include<iostream>
#include<cstdio>
#include<algorithm>
#define MAX_V 16000
using namespace std;
int tot,n,fa[MAX_V];

struct edge{
    int from,to,cost;
}es[MAX_V<<1];

bool cmp(edge a,edge b)
{
    return a.cost<b.cost;
}

int find(int x)
{
    if(x==fa[x])return x;
    else return fa[x]=find(fa[x]);
}
bool judge(int x,int y)
{
    int root1,root2;
    root1=find(x);
    root2=find(y);
    if(root1==root2) return false;
    else 
    {
        fa[root2]=root1;
        return true;
    }
}
void kruskal()
{
    int ltotal=0,flag=0,sum=0;
    for(int i=1;i<=n;i++)fa[i]=i;
    sort(es+1,es+tot+1,cmp);
    for(int i=1;i<=tot;i++)//tot表示几条边 
    {
        if(judge(es[i].from ,es[i].to ))
        {
            ltotal++;//记录边的总数 
            sum+=es[i].cost;        
        } 
        if(ltotal==n-1)
        {
            printf("%d\n",sum);
            break;
        }
    }
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
        {
            int x;
            scanf("%d",&x);
            if(x!=0)
            {
                es[++tot].from=i;
                es[tot].to=j;
                es[tot].cost=x;
            }
        }
    kruskal();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值