class Main {
static class UnionFind {
private int [] father;
UnionFind(int n) {
father = new int[n];
// init with their index
for (int i = 0; i < n; ++ i) {
father[i] = i;
}
}
//a: employer
//b: employee
public void union(int a, int b) {
int fa = find(a);
int fb = find(b);
if (fa != fb) father[fb] = father[fa];
}
public int find(int a) {
if (a == father[a]) return a;
return father[a] = find(father[a]);
}
}
public static void main(String[] args) {
// 1. Simulator of input
int [][] input = new int[][]{
{'A', 'B'},
{'B', 'C'},
{'C', 'D'}
};
int m = input.length;
int n = input[0].length;
System.out.println(m + "\n"+ n);
for (int i = 0; i < m; ++ i) {
for (int j = 0; j < n; ++ j) {
System.out.println((char)(input[i][j]));
}
}
// 2. Def union find
int ASCII_SIZE = 256;
// 0 1 2 ... 65(A) 66(B) ... 255
// 0 1 3 ... 65(A) 66(B) ... 255
UnionFind uf = new UnionFind(ASCII_SIZE);
// 3. Union
for (int i = 0; i < m; ++ i) {
uf.union(input[i][0], input[i][1]);
}
// 4. Ouptut
// the input[0][0] can be any one which is valid
System.out.println(uf.find(input[2][1]));
}
}
Union Find
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- quick-find、quick-union、加權(quán)quick-union(附帶路徑壓縮優(yōu)化) 本算法主要解決動態(tài)連...
- Quick Find 數(shù)組的每個位置存相應(yīng)的節(jié)點(diǎn)id,相連接的節(jié)點(diǎn)的位置存相同的id。判斷是否相連(connect...
- quick-find、quick-union、加權(quán)quick-union(附帶路徑壓縮優(yōu)化) 本算法主要解決動態(tài)連...
- 問題: 輸入數(shù)據(jù)必須為(0,n)?輸入數(shù)據(jù)是(0-n),初始化的時候會把id[]中的值賦值為(0-n)的數(shù) uni...