class UnionFind {
int[] data;
public UnionFind(int n) {
data = new int[n];
for (int i = 0; i < data.length; i++) {
data[i] = i;
}
}
private int findRoot(int cur) {
//路劲压缩,避免查找树过长
return cur == data[cur] ? cur : (data[cur] = findRoot(data[cur]));
}
public void union(int a, int b) {
data[findRoot(a)] = findRoot(b);
}
public boolean isSame(int a, int b) {
return findRoot(a) == findRoot(b);
}
}
并查集简单实现
最新推荐文章于 2024-07-29 12:12:13 发布