Last active
May 13, 2017 12:49
-
-
Save dance2die/27b1c7f81bbc459c4dd7f85892f4b84e to your computer and use it in GitHub Desktop.
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
internal class QuickUnionUF | |
{ | |
private readonly int[] _id; | |
private readonly int[] _size; | |
public QuickUnionUF(int n) | |
{ | |
_id = new int[n + 1]; | |
_size = new int[n + 1]; | |
for (int i = 0; i < n; i++) | |
{ | |
_id[i] = i; | |
_size[i] = 1; | |
} | |
} | |
private int GetRoot(int i) | |
{ | |
while (i != _id[i]) | |
i = _id[i]; | |
return i; | |
} | |
public bool IsConnected(int p, int q) | |
{ | |
return GetRoot(p) == GetRoot(q); | |
} | |
public void Union(int p, int q) | |
{ | |
int i = GetRoot(p); | |
int j = GetRoot(q); | |
if (i == j) return; | |
if (_size[i] < _size[j]) | |
{ | |
_id[i] = j; | |
_size[j] += _size[i]; | |
} | |
else | |
{ | |
_id[j] = i; | |
_size[i] += _size[j]; | |
} | |
} | |
public int GetMaximumConnectedRoute() | |
{ | |
return _size.Max(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment