int p[1000005], r[1000005]; int n;//一共有n个元素 void init()//初始化集合,每个元素的老板都是自己 { for (int i = 0; i < n; i++) { p[i] = i; } } int find(int x)//查找元素x的老板是谁 { if (x == p[x]) return x; else return p[x] = find(p[x]); } void join(int x, int y)//合并两个集合 { int xRoot = find(x); int yRoot = find(y); if (xRoot == yRoot) //老板相同,不合并 return; if (r[xRoot] < r[yRoot]) //r[i]是元素i所在树的高度,矮树的根节点认高树的根节点做老板 p[xRoot] = yRoot; else if (r[xRoot] > r[yRoot]) p[yRoot] = xRoot; else { p[yRoot] = xRoot;//树高相同,做老板的树高度要加一 r[xRoot]++; } } bool sameRoot(int x, int y)//查询两个元素的老板是否相同 { return find(x) == find(y); }
原文:https://www.cnblogs.com/-citywall123/p/10713285.html