并查集(用于不相交集合的数据结构)
并查集并查集保持一组不相交的动态集合S={S1, S2, ..., SK}.每个集合通过一个代表来表示,代表即集合中的某个成员。并查集的精髓(即它的三种操作):集合中的每一个元素是由一个对象表示的,设x表示一个对象
MAKE-SET(x)建立一个新的集合,其唯一成员(因而其代表)就是x。因为各个集合是不相交的,故要求x没有在其他集合中出现过。初始化后每一个元素的父亲节点是它本身,每一个元素的祖先节点也是它本身
示例代码
#include <stdio.h>#include <stdlib.h>int father[10000001];int number[10000001];int max;int find_set(int x);void union_set(int x, int y);int main(){int i, n, x, y;while (scanf("%d", &n) != EOF) {// 初始化集合for (i = 1; i <= 10000001; i ++) {father[i] = i;number[i] = 1;}// 合并并查集max = 1;for (i = 0; i < n; i ++) {scanf("%d %d", &x, &y);union_set(x, y);}// 输出结果printf("%d\n", max);}return 0;}int find_set(int x){while (x != father[x]) {x = father[x];}return x;}void union_set(int x, int y){int fx, fy;fx = find_set(x);fy = find_set(y);if (fx != fy) {number[fy] += number[fx];number[fx] = number[fy];father[fx] = fy;if (number[fy] > max) {max = number[fy];}}}