zoukankan      html  css  js  c++  java
  • 最小生成树 kruskal算法

     1 #include<stdio.h>
     2 #include<algorithm>
     3 struct Edge
     4 {
     5     int u,v,w;
     6 }edge[10010];
     7 int n,m,sett[110];
     8 int cmp(const struct Edge x,const struct Edge y)
     9 {
    10     return x.w < y.w;
    11 }
    12 int ffind(int x)
    13 {
    14     if(x != sett[x])
    15         x = ffind(sett[x]);
    16     return x;
    17 }
    18 int kruskal()
    19 {
    20     int i;
    21     for(i = 1; i <= n; i++)
    22         sett[i] = i;
    23     std::sort(edge, edge+m, cmp);
    24     int cnt = 0;
    25     for(i = 0; i < m; i++)
    26     {
    27         int x=ffind(edge[i].u);
    28         int y=ffind(edge[i].v);
    29         if(x!=y)
    30         {
    31             sett[x] = y;
    32             cnt += edge[i].w;
    33         }
    34     }
    35     return cnt;
    36 }
    37 int main ()
    38 {
    39     while(~scanf("%d %d",&n,&m))
    40     {
    41         for(int i = 0;i < m; i++)
    42             scanf("%d %d %d",&edge[i].u,&edge[i].v,&edge[i].w);
    43         printf("%d\n",kruskal());
    44     }
    45     return 0;
    46 }
  • 相关阅读:
    区别Lua模式匹配中 %a+ 与 .-
    将硬件规定的通信协议用Lua实现(涉及到很多Lua通信的数据转换)
    Lua库-string库
    Unity3d
    Unity3d
    Unity3d
    Unity3d
    Unity3d
    Unity3d
    Unity3d
  • 原文地址:https://www.cnblogs.com/LK1994/p/3019282.html
Copyright © 2011-2022 走看看