Skip to content

Instantly share code, notes, and snippets.

@dabasajay
Created January 26, 2021 16:27
Show Gist options
  • Save dabasajay/8034019d1e4a18fd2cee61b87127f743 to your computer and use it in GitHub Desktop.
Save dabasajay/8034019d1e4a18fd2cee61b87127f743 to your computer and use it in GitHub Desktop.
dsa/graphs/dsu | desc: disjoint set union dsu
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int arr[N];
void initialze(int n){
for (int i = 0; i < n; i++) arr[i] = -1;
}
int _find(int key){
if (arr[key] < 0) return key;
return arr[key] = _find(arr[key]); // Path compression
}
void _union(int a, int b){
int par_a = _find(a);
int par_b = _find(b);
if (par_a == par_b) return;
if (arr[par_a] > arr[par_b]) swap(par_a, par_b);
arr[par_a] += arr[par_b]; // Update size
arr[par_b] = par_a; // Update parent of B
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment