MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / DSU

Class DSU

MinimumCostWalkInWeightedGraph.java:1–33  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class DSU {
2 int rank[];
3 int parent[];
4 DSU(int n){
5 rank = new int[n]; //0
6 parent = new int[n];
7 for(int i=0;i<n;i++){
8 parent[i] = i;
9 }
10 }
11 public int find(int node){
12 if(node == parent[node]){
13 return node;
14 }
15 parent[node] = find(parent[node]);
16 return parent[node];
17 }
18 public void union(int node1, int node2){
19 int rootParent1 = find(node1);
20 int rootParent2 = find(node2);
21 if(rootParent1 == rootParent2){
22 return;
23 }
24 if(rank[rootParent1] < rank[rootParent2]){
25 parent[rootParent1] = rootParent2;
26 }else if(rank[rootParent2] < rank[rootParent1]){
27 parent[rootParent2] = rootParent1;
28 }else{
29 parent[rootParent2] = rootParent1;
30 rank[rootParent1]++;
31 }
32 }
33}
34
35class Solution {
36 // tc: 2v + n + m

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected