码迷,mamicode.com
首页 > 其他好文 > 详细

codevs 2627 村村通

时间:2017-01-17 23:06:26      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:ted   bre   距离   数据   帮助   tput   class   stream   target   

时间限制: 1 s
 空间限制: 32000 KB
 题目等级 : 黄金 Gold
题目描述 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

暂时无范围。

传送门

kruskal 
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

struct node{
    int x,y,z;
}e[101*101];
int j,i,n,tot;
int fa[101];
bool cmp(node a,node b)
{
    return a.z<b.z;
}
int find(int k)
{
    if(fa[k]==k) return k;
    else find(fa[k]);
}
int main()
{
    int a;
    cin>>n;
    for(i=1;i<=n;++i) fa[i]=i;
    for(i=1;i<=n;++i){
        for(j=1;j<=n;++j)
        {
            cin>>a;
            if(a)
            {
                tot++;
                e[tot].x=i;
                e[tot].y=j;
                e[tot].z=a;
            }
        }
    }
    int ans=0,k=0;
    sort(e+1,e+1+tot,cmp);
    for(i=1;i<=tot;++i)
    {
        int fx=find(e[i].x),fy=find(e[i].y);
        if(fx!=fy)
        {
            fa[fy]=fx;
            ans+=e[i].z;
            k++;
        }
        if(k==n-1) break;
    }
    cout<<ans;
}

 

 

codevs 2627 村村通

标签:ted   bre   距离   数据   帮助   tput   class   stream   target   

原文地址:http://www.cnblogs.com/ruojisun/p/6294765.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!