一个最小生成树的题目,用并查集判连通。地址:http://acm.pku.edu.cn/JudgeOnline/problem?id=1679
#include <stdio.h>
#include <stdlib.h>
const int LEN = 105;
struct
{
int b;
int e;
int len;
int flag;
}seg[LEN*LEN];
int cmp ( const void *a, const void *b )
{
return *( ( int * )a + 2 ) - *( ( int * )b + 2 );
}
int p[LEN];
void make ( int n )
{
for ( int i=0; i<n; i++ )
{
p[i] = -1;
}
}
int find ( int a )
{
if ( p[a] < 0 )
{
return a;
}
int r = find ( p[a] );
p[a] = r;
return r;
}
void un ( int a, int b )
{
int ra = find ( a );
int rb = find ( b );
if ( p[ra] < p[rb] )
{
p[ra] += p[rb];
p[rb] = ra;
}
else
{
p[rb] += p[ra];
p[ra] = rb;
}
}
int temp[LEN];
int pt;
int data[LEN];
int pd;
int kul ( int n, int m, int *ans )
{
*ans = 0;
pt = 0;
make ( n );
for ( int i=0; i<m; i++ )
{
if ( seg[i].flag )
{
seg[i].flag = 0;
continue;
}
if ( find ( seg[i].b ) != find ( seg[i].e ) )
{
un ( seg[i].b, seg[i].e );
*ans = *ans + seg[i].len;
temp[pt++] = i;
}
}
int r = find ( 0 );
for ( i=1; i<n; i++ )
{
if ( find ( i ) != r )
{
break;
}
}
if ( i < n )
{
return 0;
}
return 1;
}
int main ()
{
int t;
int n, m;
int b, e, len;
scanf ( "%d", &t );
while ( t -- )
{
scanf ( "%d%d", &n, &m );
for ( int i=0; i<m; i++ )
{
scanf ( "%d%d%d" , &b, &e, &len );
seg[i].b = b-1;
seg[i].e = e-1;
seg[i].len = len;
seg[i].flag = 0;
}
qsort ( seg, m, sizeof ( seg[0] ), cmp );
int min;
kul ( n, m, &min );
for ( i=0; i<pt; i++ )
{
data[i] = temp[i];
}
pd = pt;
for ( i=0; i<pd; i++ )
{
int temp;
seg[ data[i] ].flag = 1;
if ( kul ( n, m, &temp ) )
{
if ( temp == min )
{
break;
}
}
}
if ( i >= pd )
{
printf ( "%d\n", min );
}
else
{
printf ( "Not Unique!\n" );
}
}
return 0;
}