Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created January 11, 2018 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/cb889def70be4563581113daa8a8fb2a to your computer and use it in GitHub Desktop.
Save jianminchen/cb889def70be4563581113daa8a8fb2a to your computer and use it in GitHub Desktop.
Learn quick union algorithm - what is quick? what is union? quick is to connect one group's root to another's group root, union is connecting two trees.
/// <summary>
/// understanding the quick union
/// http://blog.csdn.net/dm_vincent/article/details/7655764
/// </summary>
public class QuickUnion
{
private int[] id; // access to component id (site indexed)
private int count; // number of components
public QuickUnion(int N)
{
// Initialize component id array.
count = N;
id = new int[N];
for (int i = 0; i < N; i++)
{
id[i] = i;
}
}
public int GetCount()
{
return count;
}
public bool Connected(int p, int q)
{
return Find(p) == Find(q);
}
/// <summary>
/// quick find algorithm Find method
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
public int Find_QuickFind(int p)
{
return id[p];
}
/// <summary>
/// quick union algorithm Find method
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
private int Find(int p)
{
// Look for node p's group root node,
// root node can be determined by id[root] = root.
while (p != id[p])
{
p = id[p];
}
return p;
}
/// <summary>
/// quick find algorithm Union
/// </summary>
/// <param name="p"></param>
/// <param name="q"></param>
public void Union_quickFind(int p, int q)
{
int pID = Find(p);
int qID = Find(q);
if (pID == qID)
{
return;
}
// Find the pID, and make them one group
for (int i = 0; i < id.Length; i++)
{
if (id[i] == pID)
{
id[i] = qID;
}
}
// update count of groups
count--;
}
/// <summary>
/// quick union algorithm Union method
/// </summary>
/// <param name="p"></param>
/// <param name="q"></param>
public void Union(int p, int q)
{
// Give p and q the same root.
int pRoot = Find(p);
int qRoot = Find(q);
if (pRoot == qRoot)
{
return;
}
// 将一颗树(即一个组)变成另外一课树(即一个组)的子树
// set one tree to another tree's subtree
id[pRoot] = qRoot;
// update count of groups
count--;
}
}
@jianminchen
Copy link
Author

March 26, 2019
Good to read the comment about quick and union.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment