kruskal+ 并查集

#include <iostream>
#include <stdio.h>
#include <string.h> 
#define MAX 20
using namespace std;
struct edge
{
       int u, v, w;
}edges[MAX];
int parent[MAX];
int n, m;
int i, j;
void UFset( )
{
     for( i = 1; i <= n; i++ )  parent[i] = -1;
}
int Find( int x )
{
    int s;
    for( s = x; parent[s] >= 0; s = parent[s] );
    while( s != x )
    {
           int tmp = parent[x];
           parent[x] = s;
           x = tmp;
    }
    return s;
}
void Union( int R1, int R2 )
{
     int temp;
     int r1 = Find( R1 );
     int r2 = Find( R2 );
     int tmp = parent[r1] + parent[r2];
     if( parent[r1] > parent[r2] )          //  r2 > r1
     {
         parent[r1] = r2;
         parent[r2] = tmp;
     }
     else
     {
         parent[r2] = r1;
         parent[r1] = temp;
     }
}
int cmp( const void * a, const void *b )
{
    edge aa = *(const edge *)a; edge bb = *( const edge *)b;
    return aa.w-bb.w;
}
void kruskal() 
{
     int sumweight = 0;
     int num = 0;
     int u, v;
     UFset( );
     for( i = 0; i < m; i++ )
     {
          u = edges[i].u; v = edges[i].v;
          if( Find( u ) != Find(v) )
          {
              printf( "%d %d %d\n", u, v, edges[i].w );
              sumweight += edges[i].w; num++;
              Union( u, v );           
          }
          if( num >= n-1 )
              break;
     }
     printf( "weight of MST is %d\n", sumweight );
}
int main()
{
    int u, v, w;
    scanf( "%d%d", &n, &m );
    for( int i = 0; i < m; i++ )
    {
         scanf( "%d%d%d", &u, &v, &w );
         edges[i].u = u; edges[i].v = v; edges[i].w = w;
    }
    qsort( edges, m, sizeof(edges[0]), cmp );
    kruskal();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值