Created
November 5, 2015 18:24
-
-
Save ashwath10110/ea459e68957448a8be07 to your computer and use it in GitHub Desktop.
Simple Union-Find Datastructure in C#
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
namespace Programming.Data_Structures.Union_Find | |
{ | |
public class UF | |
{ | |
public int[] id { get; set; } | |
public int[] sz { get; set; } | |
public int cnt { get; set; } | |
public UF(int N) | |
{ | |
cnt = N; | |
id = new int[N]; | |
sz = new int[N]; | |
for (int i = 0; i < N; i++) | |
{ | |
id[i] = i; | |
sz[i] = 1; | |
} | |
} | |
// Return the id of component corresponding to object p. | |
public int find(int p) | |
{ | |
int root = p; | |
while (root != id[root]) | |
root = id[root]; | |
while (p != root) | |
{ | |
int newp = id[p]; | |
id[p] = root; | |
p = newp; | |
} | |
return root; | |
} | |
public void merge(int x, int y) | |
{ | |
int i = find(x); | |
int j = find(y); | |
if (i == j) return; | |
if (sz[i] < sz[j]) | |
{ | |
id[i] = j; | |
sz[j] += sz[i]; | |
} | |
else | |
{ | |
id[j] = i; | |
sz[i] += sz[j]; | |
} | |
cnt--; | |
} | |
public bool connected(int x, int y) | |
{ | |
return find(x) == find(y); | |
} | |
public int count() | |
{ | |
return cnt; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hm