题目
Kruskal 构建最小生成树
#include <stdio.h>
#include <string.h>
struct edge{
int u;
int v;
int w;
} ;
struct edge e[ 10005 ] ;
int n, m;
int f[ 10005 ] = { 0 } , sum, count;
void quick_sort ( int left, int right) {
int i, j;
struct edge t;
if ( left> right)
return ;
i= left;
j= right;
while ( i< j) {
while ( i< j&& e[ j] . w >= e[ left] . w)
j-- ;
while ( i< j&& e[ i] . w <= e[ left] . w)
i++ ;
if ( i< j) {
t= e[ i] ;
e[ i] = e[ j] ;
e[ j] = t;
}
}
t= e[ left] ;
e[ left] = e[ i] ;
e[ i] = t;
quick_sort ( left, i- 1 ) ;
quick_sort ( i+ 1 , right) ;
return ;
}
int getf ( int v) {
if ( f[ v] == v)
return v;
else {
f[ v] = getf ( f[ v] ) ;
return f[ v] ;
}
}
int merge ( int v, int u) {
int t1, t2;
t1= getf ( v) ;
t2= getf ( u) ;
if ( t1!= t2) {
f[ t2] = t1;
return 1 ;
}
return 0 ;
}
int main ( ) {
int i, flag= 0 ;
while ( scanf ( "%d %d" , & n, & m) && n!= 0 ) {
sum= 0 ;
count= 0 ;
flag= 0 ;
memset ( e, 0 , sizeof ( e) ) ;
memset ( f, 0 , sizeof ( f) ) ;
for ( i= 1 ; i<= m; i++ )
f[ i] = i;
for ( i= 1 ; i<= n; i++ )
scanf ( "%d %d %d" , & e[ i] . u, & e[ i] . v, & e[ i] . w) ;
quick_sort ( 1 , n) ;
for ( i= 1 ; i<= n; i++ ) {
if ( merge ( e[ i] . u, e[ i] . v) ) {
count++ ;
sum= sum+ e[ i] . w;
}
if ( count== m- 1 )
break ;
}
for ( i= 2 ; i<= m; i++ ) {
if ( merge ( 1 , i) ) {
flag= 1 ;
break ;
}
}
if ( flag== 0 )
printf ( "%d\n" , sum) ;
else
printf ( "?\n" ) ;
}
return 0 ;
}