Prim 算法:
void Prim(int n)
{
int i,j,min_i,Min,sum=0;
int dis[501];
int flag[501];
for( i=1 ; i <= n ; i++ )
dis[i] = mat[i][1];
memset( flag, 0, sizeof(flag));
flag[1] = 1;
for( i=2 ; i <= n ; i++ )
{
Min = inf;min_i=i;
for( j=2 ; j <= n ; j++ )
if(flag[j]==0 && dis[j]<Min)
{
Min = dis[j];
min_i = j;
}
if(Min == inf) break;
sum += Min;
flag[min_i] = 1;
for( j=2 ; j <= n ; j++ )
{
if(flag[j]==0 && dis[j]>mat[min_i][j])
dis[j] = mat[min_i][j];
}
}
printf("%d\n", sum);
}
Kruskal 算法:
int fa[N],n,m;
struct edge
{
int x,y,value;
}e[N];
bool cmp(edge a,edge b)
{
return a.value < b.value;
}
int find(int x)
{
if(x==fa[x]) return x;
return fa[x]=find(fa[x]);
}
void Kruskal()
{
int ans = 0;
for(int i=0 ; i <= n ; ++i) fa[i] = i;
sort(e,e+m,cmp);
for(int i=0 ; i < m ; ++i)
{
int x = find(e[i].x);
int y = find(e[i].y);
if(x != y)
{
ans += e[i].value;
fa[x] = y;
}
}
printf("%d\n",ans);
}