并查集,其实kruskal算法里用过,不过不熟练,感觉代码还可以改进,懒的优化了,明天还要上班。。好困,睡觉去鸟
#include<stdio.h>
#include<stdlib.h>
struct StudentStruct
{
int id;
struct StudentStruct *parent;
int rank;
};
typedef struct StudentStruct *Student;
Student make_set(int id)
{
Student stu = malloc(sizeof(struct StudentStruct));
stu->parent = stu;
stu->id = id;
stu->rank = 1;
return stu;
}
Student find_set(Student stu)
{
if (stu->parent != stu)
stu->parent = find_set(stu->parent);
return stu->parent;
}
static void link(Student s1, Student s2)
{
if (s1->rank > s2->rank)
{
s2->parent = s1;
s1->rank += s2->rank;
}
else
{
s1->parent = s2;
s2->rank += s1->rank;
}
}
static void union_set(Student s1, Student s2)
{
link(find_set(s1), find_set(s2));
}
int main()
{
int n, m;
Student *array = malloc(30000 * sizeof(Student));
while (scanf("%d %d", &n, &m), n || m)
{
int i, j, k, id;
for (i = 0; i < n; i++)
array[i] = NULL;
for (i = 0; i < m; i++)
{
scanf("%d", &k);
Student head;
if (k)
{
scanf("%d", &id);
if (array[id] == NULL)
array[id] = make_set(id);
head = find_set(array[id]);
}
for (j = 1; j < k; j++)
{
scanf("%d", &id);
if (array[id] == NULL)
array[id] = make_set(id);
if (find_set(head) != find_set(array[id]))
union_set(head, array[id]);
}
}
if (array[0] == NULL)
puts("1");
else
printf("%d\n", find_set(array[0])->rank);
}
free(array);
return 0;
}
本文探讨了并查集在Kruskal算法中的使用,并分享了代码实现及优化思考,涉及数据结构和算法优化。
1595

被折叠的 条评论
为什么被折叠?



