codevs 1231_最优布线问题_最小生成树

来源:互联网 发布:手机淘宝产品链接 编辑:程序博客网 时间:2024/04/30 04:06

题目描述

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

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


思路

就是一个最小生成树问题,这里因为数据大,用了并查集+kruskal,暴力一下就可以了
O(nlogn)


#include <stdio.h>#include <algorithm>using namespace std;int f[100001];struct arr{    int x,y,z;};arr a[100001];int cam(arr x,arr y){    return x.z<y.z;}int find(int x){    if (!f[x]) return x;    f[x]=find(f[x]);    return f[x];}int insert(int x,int y){    if (find(x)!=find(y))    {        f[find(x)]=find(y);        return 1;    }    return 0;}int main(){    int n,m;    scanf("%d%d",&n,&m);    for (int i=1;i<=m;i++)        scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].z);    sort(a+1,a+m+1,cam);    long long tot=0;    for (int i=1;i<=m;i++)    {        if (find(a[i].x)!=find(a[i].y))        {            tot+=a[i].z;            insert(a[i].x,a[i].y);        }    }    printf("%lld\n",tot);}
1 0