Skip to content

Instantly share code, notes, and snippets.

@ashwath10110
Created November 5, 2015 18:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ashwath10110/ea459e68957448a8be07 to your computer and use it in GitHub Desktop.
Save ashwath10110/ea459e68957448a8be07 to your computer and use it in GitHub Desktop.
Simple Union-Find Datastructure in C#
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;
}
}
}
@IDiamondDragon
Copy link

hm

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