T1231 最优布线 codevs

http://codevs.cn/problem/1231/

 时间限制: 1 s
 空间限制: 128000 KB
 题目等级 : 白银 Silver
题目描述 Description

学校需要将n台计算机连接起来,不同的2台计算机之间的连接费用可能是不同的。为了节省费用,我们考虑采用间接数据传输结束,就是一台计算机可以间接地通过其他计算机实现和另外一台计算机连接。

为了使得任意两台计算机之间都是连通的(不管是直接还是间接的),需要在若干台计算机之间用网线直接连接,现在想使得总的连接费用最省,让你编程计算这个最小的费用。

输入描述 Input Description

输入第一行为两个整数n,m(2<=n<=100000,2<=m<=100000),表示计算机总数,和可以互相建立连接的连接个数。接下来m行,每行三个整数a,b,c 表示在机器a和机器b之间建立连接的话费是c。(题目保证一定存在可行的连通方案, 数据中可能存在权值不一样的重边,但是保证没有自环)

输出描述 Output Description

输出只有一行一个整数,表示最省的总连接费用。

样例输入 Sample Input

3 3

1 2 1

1 3 2

2 3 1

样例输出 Sample Output

2

数据范围及提示 Data Size & Hint

最终答案需要用long long类型来保存

#include <algorithm>
#include <iostream>
#include <cstdio>
#define maxn 100001

using namespace std;

typedef long long LL;
int n,m,a,b,c,tot,num=0;
LL ans=0;
int fa[maxn];
struct node
{
    int u,v,w; 
}e[maxn];

void add(int x,int y,int z)
{
    tot++;
    e[tot].u=x;
    e[tot].v=y;
    e[tot].w=z;
}

int find(int x)
{
    if(x!=fa[x])
        fa[x]=find(fa[x]);
    return x;
}

bool cmp(node aa,node bb)
{
    return aa.w<bb.w;
}

int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)    fa[i]=i;
    for(int i=1;i<=m;i++)
    {
        scanf("%d%d%d",&a,&b,&c);
        add(a,b,c);
    }
    sort(e+1,e+tot+1,cmp);
    for(int i=1;i<=tot;i++)
    {
        int xx=find(e[i].u),yy=find(e[i].v);
        if(xx!=yy)
        {
            fa[yy]=xx;
            num++;
            ans+=e[i].w;
            if(num==n-1)
                break;
        }
        
    }
    printf("%lld",ans);
    return 0;
}
——每当你想要放弃的时候,就想想是为了什么才一路坚持到现在。
原文地址:https://www.cnblogs.com/Shy-key/p/6538895.html