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

最小生成树之Kruskal

时间:2017-06-18 17:24:53      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:排序   mic   ams   int   names   return   microsoft   nod   str   

思路:(贪心)

排序边的权值,按从小到大排序,然后从最小权值开始,一直连接点(把他们的父亲变成同一个),最后连成的树就是最小生成树

代码实现(hdu 1233)

#include <stdio.h>
#include <iostream>
#include <algorithm>
using namespace std;
int v[100006];
struct node
{
    int x,y,len;
}road[10006];
int f(int a)
{
    return a==v[a]?a:f(v[a]);
}
bool cmp(node a,node b)
{
    return a.len<b.len?1:0;
}
int main()
{

    int n,ans=0;
    while(scanf("%d",&n),n)
    {
        for(int i=1;i<=n;i++)
    	v[i]=i;
    	ans=0;
        int ans = 0;
        int t = n*(n-1)/2;
        for(int i=0;i<t;i++)
        {
            scanf("%d %d %d",&road[i].x,&road[i].y,&road[i].len);
        }
        sort(road,road+t,cmp);
        for(int i=0;i<t;i++)
        {
        	//cout<<n<<endl;
            int fa = f(road[i].x);
            int fb = f(road[i].y);
            if(fa!=fb)
            {
                ans+=road[i].len;
                v[fa] = fb;
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}

最小生成树之Kruskal

标签:排序   mic   ams   int   names   return   microsoft   nod   str   

原文地址:http://www.cnblogs.com/chinacwj/p/7044593.html

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