Kruskal 算法
注意数组不要越界,尽量开大点,其他没什么注意,这种算法的水题
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <iostream>
//#define T
///
using namespace std;
const int M = 220;
int f[M];
struct edge
{
int x;
int y;
int u;
};
edge e[10000];
void s_union(int a, int b);
bool cmp(edge a,edge b);
int f_find(int a);
int counter;
int ans;
int n,m;
void inital()
{
for(int i = 0; i <= 200; i ++)
f[i] = i;
counter = 1;
}
bool cmp(edge a,edge b)
{
return a.u < b.u;
}
int f_find(int a)
{
if(a != f[a])
f[a] = f_find(f[a]);
return f[a];
}
void s_union(int a, int b)
{
if(a > b)
f[b] = a;
else
f[a] = b;
}
int main()
{
int l,i,j,r;
while(~scanf("%d %d",&n,&m) && (n||m))
{
ans = 0x3f3f3f3f;
for( i = 0; i < m; i ++)
scanf("%d %d %d",&e[i].x,&e[i].y,&e[i].u);
sort(e,e+m,cmp);
for(j = 0; j < m; j++)
{
inital();
for( i = j; i < m; i++)
{
l = f_find(e[i].x);
r = f_find(e[i].y);
if(l != r)
{
s_union(l,r);
counter++;
// printf("counter ----- %d\n",counter);
}
if(counter == n)
{
ans = min(ans,e[i].u - e[j].u);
break;
}
}
}
if(ans == 0x3f3f3f3f)
printf("%d\n",-1);
else
printf("%d\n",ans);
}
return 0;
}