-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[UFDS] Add UFDS lib and client in Java
- Loading branch information
1 parent
22a326f
commit d246521
Showing
2 changed files
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
package UFDS; | ||
|
||
public class UfdsClient { | ||
public static void main(String[] args) { | ||
Ufds ufds = new Ufds(10); | ||
ufds.unionSet(1, 8); | ||
ufds.unionSet(8, 9); | ||
ufds.unionSet(8, 3); | ||
|
||
System.out.printf("is same set (1, 9): %b\n", ufds.isSameSet(1, 9)); | ||
System.out.printf("is same set (1, 4): %b\n", ufds.isSameSet(1, 4)); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
package UFDS; | ||
|
||
public class Ufds { | ||
public Ufds(int numNodes) { | ||
mNumNodes = numNodes; | ||
mRank = new int[mNumNodes]; | ||
mParentIndex = new int[mNumNodes]; | ||
|
||
for (int i = 0; i < mNumNodes; i++) { | ||
mParentIndex[i] = i; | ||
} | ||
} | ||
|
||
public int findSet(int i) { | ||
if (mParentIndex[i] == i) { | ||
return i; | ||
} | ||
|
||
mParentIndex[i] = findSet(mParentIndex[i]); | ||
return mParentIndex[i]; | ||
} | ||
|
||
public boolean isSameSet(int i, int j) { | ||
return findSet(i) == findSet(j); | ||
} | ||
|
||
public void unionSet(int i, int j) { | ||
if (isSameSet(i, j)) { | ||
return; | ||
} | ||
|
||
int iParent = findSet(i); | ||
int jParent = findSet(j); | ||
if (mRank[iParent] > mRank[jParent]) { | ||
mParentIndex[jParent] = iParent; | ||
} else { | ||
mParentIndex[iParent] = jParent; | ||
if (mRank[iParent] == mRank[jParent]) { | ||
++mRank[jParent]; | ||
} | ||
} | ||
} | ||
|
||
private final int mNumNodes; | ||
private int[] mParentIndex; | ||
private int[] mRank; | ||
} |