public class unionFindSet {
public static void main(String[] args) {
int n = 100;
node[] nodes = new node[100];
for (int i = 0; i < n; i++) {
nodes[i] = new node();
nodes[i].data = i;
nodes[i].parent = nodes[i];
}
union(nodes[1], nodes[2]);
for (int i = 0; i < nodes.length; i++) {
System.out.println(find(nodes[i]).count);
}
}
static node findzip(node n) {
n.parent = find(n);
return n.parent;
}
static node find(node n) {
if (n.parent == n)
return n;
return find(n.parent);
}
static void union(node n, node m) {
node nparent = findzip(n);
node mparent = findzip(m);
nparent.count = nparent.count + mparent.count;
mparent.parent = nparent;
}
static class node {
int data;
int count = 1;
node parent;
}
}
}
原文:https://www.cnblogs.com/continued258/p/12459393.html