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\n",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)

posted @ 2017-06-27 15:02  Michael_Zhuang  阅读(138)  评论(0编辑  收藏  举报