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

克鲁斯卡尔

时间:2017-10-19 17:39:19      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:namespace   const   logs   cstring   names   ==   blog   ret   ios   

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
using namespace std;
int f[100000];
struct node
{
    int a;
    int b;
    int c;
}s[100000];
bool cmp(const node & x,const node & y){return x.c<y.c;}
int fuqin(int h)
{
    if(f[h]==h) return h;
    else
    {
        f[h]=fuqin(f[h]);
        return f[h];
    }
}
int main()
{
    int n;
    int m;
    cin>>n>>m;
    int i,j,k;
    for(i=1;i<=m;i++)
    {
        cin>>s[i].a>>s[i].b>>s[i].c;
    }
    for(i=1;i<=n;i++) f[i]=i;
    sort(s+1,s+m+1,cmp);
    int ans=0,maxx=0;
    for(i=1;i<=m;i++)
    {
        int h1=fuqin(s[i].a);
        int h2=fuqin(s[i].b);
        if(h1!=h2)
        {
            f[h2]=h1;
            maxx++;
            ans+=s[i].c;
        }
        if(maxx==n-1)
            break;
    }
    cout<<ans;
    return 0;
}
/*
5
6
1 2 2
2 3 1
2 3 2
3 4 3
4 5 2
5 4 9
*/

克鲁斯卡尔的核心是,给边排序。选出每两个点的最短路径。直到图连通,需要n-1条边。

克鲁斯卡尔

标签:namespace   const   logs   cstring   names   ==   blog   ret   ios   

原文地址:http://www.cnblogs.com/WWHHTT/p/7693524.html

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