您的位置:首页 > 其它

ZOJ-1789

2014-04-15 00:25 169 查看
并查集,其实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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: