module DisjointSetSimple = struct type universe = int array let createUniverse (size : int) : universe = Array.init size (fun i -> i) let rec find (s : universe) (e : int) : int = let p = s.(e) in if p = e then e else find s p let union (s : universe) (e1 : int) (e2 : int) : unit = let r1 = find s e1 and r2 = find s e2 in s.(r1) <- r2 end module DSS = DisjointSetSimple;; let s1 = DSS.createUniverse 12;; DSS.union s1 0 4;; DSS.union s1 4 6;; DSS.union s1 11 5;; DSS.union s1 3 5;; DSS.union s1 6 2;; DSS.union s1 8 2;; DSS.union s1 1 7;; DSS.union s1 5 7;; DSS.union s1 9 7;; DSS.union s1 3 9;; DSS.union s1 0 8;; s1;; [DSS.find s1 0; DSS.find s1 1; DSS.find s1 2; DSS.find s1 3; DSS.find s1 4; DSS.find s1 5; DSS.find s1 6; DSS.find s1 7; DSS.find s1 8; DSS.find s1 9; DSS.find s1 10; DSS.find s1 11];; (* *) module DisjointSet = struct type node = {mutable parent : int; mutable rank : int} type universe = node array let createUniverse (size : int) : universe = Array.init size (fun i -> {parent = i; rank = 0}) let rec find (s : universe) (e : int) : int = let n = s.(e) in if n.parent = e then e else (n.parent <- (find s n.parent); n.parent) let union (s : universe) (e1 : int) (e2 : int) : unit = let r1 = find s e1 and r2 = find s e2 in let n1 = s.(r1) and n2 = s.(r2) in if r1 != r2 then if n1.rank < n2.rank then n1.parent <- r2 else (n2.parent <- r1; if n1.rank = n2.rank then n1.rank <- n1.rank + 1) end module DS = DisjointSet;; let s2 = DS.createUniverse 12;; DS.union s2 0 4;; DS.union s2 4 6;; DS.union s2 11 5;; DS.union s2 3 5;; DS.union s2 6 2;; DS.union s2 8 2;; DS.union s2 1 7;; DS.union s2 5 7;; DS.union s2 9 7;; DS.union s2 3 9;; DS.union s2 0 8;; s2;; [DS.find s2 0; DS.find s2 1; DS.find s2 2; DS.find s2 3; DS.find s2 4; DS.find s2 5; DS.find s2 6; DS.find s2 7; DS.find s2 8; DS.find s2 9; DS.find s2 10; DS.find s2 11];; s2;;