{"id":1039,"date":"2017-11-29T17:49:27","date_gmt":"2017-11-30T01:49:27","guid":{"rendered":"http:\/\/zxi.mytechroad.com\/blog\/?p=1039"},"modified":"2018-09-06T00:12:20","modified_gmt":"2018-09-06T07:12:20","slug":"sp1-union-find-set","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/data-structure\/sp1-union-find-set\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode Disjoint set \/ Union Find Forest SP1"},"content":{"rendered":"<p><iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 Disjoint-set\/Union-find Forest - \u5237\u9898\u627e\u5de5\u4f5c SP1\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/VJnUwsE4fWA?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<p><span style=\"font-weight: 400;\">Disjoint-set\/Union-find Forest<\/span><\/p>\n<p><span style=\"font-weight: 400;\">Find(x): find the root\/cluster-id of x<\/span><\/p>\n<p><span style=\"font-weight: 400;\">Union(x, y): merge two clusters<\/span><\/p>\n<p><span style=\"font-weight: 400;\">Check whether two elements are in the same set or not in O(1)<\/span><span style=\"font-weight: 400;\">*<\/span><span style=\"font-weight: 400;\">.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">Find: O(\u0251(n))<\/span><span style=\"font-weight: 400;\">*<\/span><span style=\"font-weight: 400;\"> \u2248 O(1)<\/span><\/p>\n<p><span style=\"font-weight: 400;\">Union: <\/span><span style=\"font-weight: 400;\">O(\u0251(n))<\/span><span style=\"font-weight: 400;\">*<\/span><span style=\"font-weight: 400;\"> \u2248 O(1)<\/span><\/p>\n<p><span style=\"font-weight: 400;\">Space: O(n)<\/span><\/p>\n<p><span style=\"font-weight: 400;\">Without optimization: Find: O(n)<\/span><\/p>\n<p><span style=\"font-weight: 400;\">Two key optimizations:<\/span><\/p>\n<ol>\n<li style=\"font-weight: 400;\"><span style=\"font-weight: 400;\">Path compression: make tree flat<\/span><\/li>\n<li style=\"font-weight: 400;\"><span style=\"font-weight: 400;\">Union by rank: merge low rank tree to high rank one<\/span><\/li>\n<\/ol>\n<p><span style=\"font-weight: 400;\">*: amortized<\/span><\/p>\n<p><span style=\"font-weight: 400;\">\u0251(.): inverse Ackermann function<\/span><\/p>\n<p><a href=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/sp1-1.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-1046\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/sp1-1.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/sp1-1.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/sp1-1-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/sp1-1-768x432.png 768w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/a><\/p>\n<p>&nbsp;<\/p>\n<p><a href=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/sp1-2.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-1045\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/sp1-2.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/sp1-2.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/sp1-2-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/sp1-2-768x432.png 768w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/a><\/p>\n<p><a href=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/sp1-3.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-1044\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/sp1-3.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/sp1-3.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/sp1-3-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/sp1-3-768x432.png 768w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/a><\/p>\n<h1>Implementations:<\/h1>\n<div class=\"responsive-tabs\">\n<h2 class=\"tabtitle\">C++<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:c++ decode:true\">\/\/ Author: Huahua\r\nclass UnionFindSet {\r\npublic:\r\n    UnionFindSet(int n) {\r\n        ranks_ = vector&lt;int&gt;(n + 1, 0);        \r\n        parents_ = vector&lt;int&gt;(n + 1, 0);                \r\n        \r\n        for (int i = 0; i &lt; parents_.size(); ++i)\r\n            parents_[i] = i;\r\n    }\r\n    \r\n    \/\/ Merge sets that contains u and v.\r\n    \/\/ Return true if merged, false if u and v are already in one set.\r\n    bool Union(int u, int v) {\r\n        int pu = Find(u);\r\n        int pv = Find(v);\r\n        if (pu == pv) return false;\r\n        \r\n        \/\/ Meger low rank tree into high rank tree\r\n        if (ranks_[pv] &lt; ranks_[pu])\r\n            parents_[pv] = pu;           \r\n        else if (ranks_[pu] &lt; ranks_[pv])\r\n            parents_[pu] = pv;\r\n        else {\r\n            parents_[pv] = pu;\r\n            ranks_[pu] += 1;\r\n        }\r\n        \r\n        return true;\r\n    }\r\n    \r\n    \/\/ Get the root of u.\r\n    int Find(int u) {        \r\n        \/\/ Compress the path during traversal\r\n        if (u != parents_[u])\r\n            parents_[u] = Find(parents_[u]);        \r\n        return parents_[u];\r\n    }\r\nprivate:\r\n    vector&lt;int&gt; parents_;\r\n    vector&lt;int&gt; ranks_;\r\n};<\/pre>\n\n<\/div><h2 class=\"tabtitle\">Java<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:java decode:true\">\/\/ Author: Huahua\r\nclass UnionFindSet {\r\n  private int[] parents_;\r\n  private int[] ranks_;\r\n\r\n  public UnionFindSet(int n) {\r\n      parents_ = new int[n + 1];\r\n      ranks_ = new int[n + 1];\r\n      for (int i = 0; i &lt; parents_.length; ++i) {\r\n          parents_[i] = i;\r\n          ranks_[i] = 1;\r\n      }\r\n  }\r\n\r\n  public boolean Union(int u, int v) {\r\n      int pu = Find(u);\r\n      int pv = Find(v);\r\n      if (pu == pv) return false;\r\n\r\n      if (ranks_[pv] &gt; ranks_[pu])\r\n          parents_[pu] = pv;           \r\n      else if (ranks_[pu] &gt; ranks_[pv])\r\n          parents_[pv] = pu;\r\n      else {\r\n          parents_[pv] = pu;\r\n          ranks_[pu] += 1;\r\n      }\r\n\r\n      return true;\r\n  }\r\n\r\n  public int Find(int u) {\r\n      while (parents_[u] != u) {\r\n          parents_[u] = parents_[parents_[u]];\r\n          u = parents_[u];\r\n      }\r\n      return u;\r\n  }\r\n}<\/pre>\n\n<\/div><h2 class=\"tabtitle\">Python<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:python decode:true\">\"\"\"\r\nAuthor: Huahua\r\n\"\"\"\r\nclass UnionFindSet:\r\n    def __init__(self, n):\r\n        self._parents = [i for i in range(n + 1)]\r\n        self._ranks = [1 for i in range(n + 1)]\r\n    \r\n    def find(self, u):\r\n        while u != self._parents[u]:\r\n            self._parents[u] = self._parents[self._parents[u]]\r\n            u = self._parents[u]\r\n        return u\r\n    \r\n    def union(self, u, v):\r\n        pu, pv = self.find(u), self.find(v)\r\n        if pu == pv: return False\r\n        \r\n        if self._ranks[pu] &lt; self._ranks[pv]:\r\n            self._parents[pu] = pv\r\n        elif self._ranks[pu] &gt; self._ranks[pv]:\r\n            self._parents[pv] = pu\r\n        else:        \r\n            self._parents[pv] = pu\r\n            self._ranks[pu] += 1\r\n        \r\n        return True<\/pre>\n<\/div><\/div>\n<h1>Union-Find Problems<\/h1>\n<ul>\n<li><a href=\"https:\/\/zxi.mytechroad.com\/blog\/graph\/leetcode-399-evaluate-division\/\">\u82b1\u82b1\u9171 LeetCode 399. Evaluate Division<\/a><\/li>\n<li><a href=\"https:\/\/zxi.mytechroad.com\/blog\/graph\/leetcode-547-friend-circles\/\">\u82b1\u82b1\u9171 LeetCode 547. Friend Circles<\/a><\/li>\n<li><a href=\"https:\/\/zxi.mytechroad.com\/blog\/hashtable\/leetcode-737-sentence-similarity-ii\/\">\u82b1\u82b1\u9171 LeetCode 737. Sentence Similarity II<\/a><\/li>\n<li><a href=\"https:\/\/zxi.mytechroad.com\/blog\/tree\/leetcode-684-redundant-connection\/\">\u82b1\u82b1\u9171 LeetCode 684. Redundant Connection<\/a><\/li>\n<li><a href=\"https:\/\/zxi.mytechroad.com\/blog\/graph\/leetcode-685-redundant-connection-ii\/\">\u82b1\u82b1\u9171 LeetCode 685. Redundant Connection II<\/a><\/li>\n<li><a href=\"https:\/\/zxi.mytechroad.com\/blog\/string\/leetcode-839-similar-string-groups\/\">\u82b1\u82b1\u9171 LeetCode 839. Similar String Groups<\/a><\/li>\n<\/ul>\n<h1><strong>References<\/strong><\/h1>\n<ul>\n<li><a href=\"https:\/\/en.wikipedia.org\/wiki\/Disjoint-set_data_structure\">https:\/\/en.wikipedia.org\/wiki\/Disjoint-set_data_structure<\/a><\/li>\n<li><a href=\"https:\/\/www.cs.princeton.edu\/courses\/archive\/spring13\/cos423\/lectures\/UnionFind.pdf\">https:\/\/www.cs.princeton.edu\/courses\/archive\/spring13\/cos423\/lectures\/UnionFind.pdf<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Disjoint-set\/Union-find Forest Find(x): find the root\/cluster-id of x Union(x, y): merge two clusters Check whether two elements are in the same set or not in&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[89,170],"tags":[28,113],"class_list":["post-1039","post","type-post","status-publish","format-standard","hentry","category-data-structure","category-sp","tag-tree","tag-union-find","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/1039","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/comments?post=1039"}],"version-history":[{"count":17,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/1039\/revisions"}],"predecessor-version":[{"id":3876,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/1039\/revisions\/3876"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=1039"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=1039"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=1039"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}