ZOJ 1372 题解
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define INT_MAX 2500
typedef struct
{
int x, y;
int w;
}edge;
edge e[INT_MAX];
int rank[INT_MAX], father[INT_MAX], dis_sum;
int cmp(const void *a,const void *b)
{
return (*(edge*)a).w > (*(edge*)b).w ? 1 : -1;
}
int Exchage(int n)
{
int i, temp;
for(i=0; i<n; i++)
{
if(e[i].x > e[i].y)
{
temp = e[i].y;
e[i].y = e[i].x;
e[i].x = temp;
}
}
}
int Make_set(int x)
{
father[x] = x;
rank[x] = 0;
}
int Find_set(int x)
{
if (x != father[x])
father[x] = Find_set(father[x]);
return father[x];
}
int Link(int x,int y,int w)
{
if(rank[x] > rank[y])
{
father[y] = x;
}
else
{
father[x] = y;
if(rank[x] == rank[y]) rank[y]++;
}
dis_sum += w;
}
int Kruskal(int point_amou,int edge_amou)
{
int i, x, y;
Exchage(edge_amou);
for(i=0; i<point_amou; i++)
{
Make_set(i);
}
qsort(e,edge_amou,sizeof(edge),cmp);
dis_sum = 0;
for(i=0; i<edge_amou; i++)
{
x = Find_set(e[i].x);
y = Find_set(e[i].y);
if(x != y)
Link(x,y,e[i].w);
}
return dis_sum;
}
int main()
{
int i, npoints, line, x, y;
while(scanf("%d", &npoints)!= EOF)
{
if(npoints == 0)
break;
else
scanf("%d", &line);
if(line == 0) printf("0\n");
if(line != 0 && npoints != 0)
{
for(i=0; i<line; i++)
{
scanf("%d %d %d",&x,&y,&e[i].w);
e[i].x = x - 1;
e[i].y = y - 1;
}
Kruskal(npoints,line);
printf("%d\n", Kruskal(npoints,line));
}
}
return 0;
}
刚刚学了最小生成树算法,用的模版解题过得很随意,AC的感觉就是好啊!哈哈~
在此给出代码与大家共享啊!