ZOJ-1789

本文探讨了并查集在Kruskal算法中的使用,并分享了代码实现及优化思考,涉及数据结构和算法优化。

并查集,其实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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值