• codevs 1231最优布线问题


    Code:

    #include <iostream>
    #include <cstdio>
    #include <algorithm>
    #include <cstdio>
    #define ll long long
    using namespace std;
    struct poi{ll x,y,cost;}p[100001];
    ll n,m,ans,fa[100001];
    bool cmp(poi a,poi b){return a.cost<b.cost;}
    int gf(ll v){return fa[v]==v?v:fa[v]=gf(fa[v]);}
    int main()
    {
        scanf("%lld %lld",&n,&m);
        for (int i=0;i<=n;i++)fa[i]=i;
        for (int i=0;i<m;i++)scanf("%lld %lld %lld",&p[i].x,&p[i].y,&p[i].cost);
        sort(p,p+m,cmp);
        for (int i=0;i<m;i++)
        {
            int x=gf(p[i].x),y=gf(p[i].y);
            if (x!=y) ans+=p[i].cost,fa[x]=y;
        }
        printf("%lld
    ",ans);
    }

     Re:

    #include <iostream>
    #include <cstdio>
    #include <algorithm>
    #define ll long long
    struct poi{ll x,y,cost;};
    using namespace std;
    poi a[100010];
    ll m,n,fa[100010];
    ll gf(int x){return x==fa[x]?x:fa[x]=gf(fa[x]);}
    bool cmp(poi x,poi y){return x.cost<y.cost;}
    int main()
    {
        scanf("%lld %lld",&n,&m);
        for (int i=0;i<=n;i++) fa[i]=i;
        for (int i=0;i<m;i++)scanf("%lld %lld %lld",&a[i].x,&a[i].y,&a[i].cost);
        sort(a,a+m,cmp);
        ll ans=0;
        for (int i=0;i<m;i++)
        {
            ll x=gf(a[i].x);ll y=gf(a[i].y);
            if (!(x==y)) ans+=a[i].cost,fa[x]=y;
        }
        printf("%lld",ans);
    }

    Kruskal 水题一枚,初转CPP练练手

    (PS:类似HF奥考机试第二题,然而我并没有看粗来,果然是蒟蒻Orz)

  • 相关阅读:
    MySQL经典练习题(四)
    MySQL经典练习题(三)
    MySQL经典练习题(二)
    MySQL经典练习题(一)
    MySQL经典练习题-数据准备
    表连接
    子查询
    MySQL中函数分类
    排序
    数据分组
  • 原文地址:https://www.cnblogs.com/mczhuang/p/7085275.html
Copyright © 2020-2023  润新知