Last active
September 15, 2023 22:06
-
-
Save AssortedFantasy/8614ed5d893a04fead17737a0e880961 to your computer and use it in GitHub Desktop.
This is useful for Leetcode problems.
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
// free with free(arr); | |
static int* new_union(int n) { | |
int* arr = malloc(sizeof(int)*n); | |
for (int i=0; i<n; i++) arr[i] = i; | |
return arr; | |
} | |
// Implements path compression | |
static int get_parent(int* arr, int i) { | |
if (arr[i] == i) return i; | |
const int parent = get_parent(arr, arr[i]); | |
arr[i] = parent; | |
return parent; | |
} | |
static void union_join(int* arr, int i, int j) { | |
const int p1 = get_parent(arr, i); | |
const int p2 = get_parent(arr, j); | |
arr[p2] = p1; | |
} | |
static bool are_joined(int* arr, int i, int j) { | |
return get_parent(arr, i) == get_parent(arr, j); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment