#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;
}
kruskal+ 并查集
最新推荐文章于 2022-07-05 01:08:50 发布