{"id":7354,"date":"2020-09-06T08:29:51","date_gmt":"2020-09-06T15:29:51","guid":{"rendered":"https:\/\/zxi.mytechroad.com\/blog\/?p=7354"},"modified":"2020-09-06T12:01:07","modified_gmt":"2020-09-06T19:01:07","slug":"leetcode-1579-remove-max-number-of-edges-to-keep-graph-fully-traversable","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/graph\/leetcode-1579-remove-max-number-of-edges-to-keep-graph-fully-traversable\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 1579. Remove Max Number of Edges to Keep Graph Fully Traversable"},"content":{"rendered":"\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n<iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 1579. Remove Max Number of Edges to Keep Graph Fully Traversable - \u5237\u9898\u627e\u5de5\u4f5c EP355\" width=\"500\" height=\"281\" src=\"https:\/\/www.youtube.com\/embed\/eTQnRrmCWBc?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>\n<\/div><\/figure>\n\n\n\n<p>Alice and Bob have an undirected graph of&nbsp;<code>n<\/code>&nbsp;nodes&nbsp;and 3 types of edges:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Type 1: Can be traversed by Alice only.<\/li><li>Type 2: Can be traversed by Bob only.<\/li><li>Type 3: Can by traversed by both Alice and Bob.<\/li><\/ul>\n\n\n\n<p>Given an array&nbsp;<code>edges<\/code>&nbsp;where&nbsp;<code>edges[i] = [type<sub>i<\/sub>, u<sub>i<\/sub>, v<sub>i<\/sub>]<\/code>&nbsp;represents a bidirectional edge of type&nbsp;<code>type<sub>i<\/sub><\/code>&nbsp;between nodes&nbsp;<code>u<sub>i<\/sub><\/code>&nbsp;and&nbsp;<code>v<sub>i<\/sub><\/code>, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes.<\/p>\n\n\n\n<p>Return&nbsp;<em>the maximum number of edges you can remove, or return<\/em>&nbsp;<code>-1<\/code>&nbsp;<em>if it&#8217;s impossible for the graph to be fully traversed by Alice and Bob.<\/em><\/p>\n\n\n\n<p><strong>Example 1:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/assets.leetcode.com\/uploads\/2020\/08\/19\/ex1.png\" alt=\"\"\/><\/figure>\n\n\n\n<pre class=\"wp-block-preformatted;crayon:false\"><strong>Input:<\/strong> n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]\n<strong>Output:<\/strong> 2\n<strong>Explanation: <\/strong>If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2.\n<\/pre>\n\n\n\n<p><strong>Example 2:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/assets.leetcode.com\/uploads\/2020\/08\/19\/ex2.png\" alt=\"\"\/><\/figure>\n\n\n\n<pre class=\"wp-block-preformatted;crayon:false\"><strong>Input:<\/strong> n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]]\n<strong>Output:<\/strong> 0\n<strong>Explanation: <\/strong>Notice that removing any edge will not make the graph fully traversable by Alice and Bob.\n<\/pre>\n\n\n\n<p><strong>Example 3:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/assets.leetcode.com\/uploads\/2020\/08\/19\/ex3.png\" alt=\"\"\/><\/figure>\n\n\n\n<pre class=\"wp-block-preformatted;crayon:false\"><strong>Input:<\/strong> n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]]\n<strong>Output:<\/strong> -1\n<strong>Explanation: <\/strong>In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable.<\/pre>\n\n\n\n<p><strong>Constraints:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code>1 &lt;= n &lt;= 10^5<\/code><\/li><li><code>1 &lt;= edges.length &lt;= min(10^5, 3 * n * (n-1) \/ 2)<\/code><\/li><li><code>edges[i].length == 3<\/code><\/li><li><code>1 &lt;= edges[i][0] &lt;= 3<\/code><\/li><li><code>1 &lt;= edges[i][1] &lt; edges[i][2] &lt;= n<\/code><\/li><li>All tuples&nbsp;<code>(type<sub>i<\/sub>, u<sub>i<\/sub>, v<sub>i<\/sub>)<\/code>&nbsp;are distinct.<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Solution: Greedy + Spanning Tree \/ Union Find<\/strong><\/h2>\n\n\n\n<p>Use type 3 (both) edges first.<\/p>\n\n\n\n<p>Time complexity: O(E)<br>Space complexity: O(n)<\/p>\n\n\n\n<div class=\"responsive-tabs\">\n<h2 class=\"tabtitle\">C++<\/h2>\n<div class=\"tabcontent\">\n\n<pre lang=\"c++\">\nclass DSU {\npublic: \n  DSU(int n): p_(n + 1), e_(0) {\n    iota(begin(p_), end(p_), 0);\n  }\n  \n  int find(int x) {\n    if (p_[x] == x) return x;\n    return p_[x] = find(p_[x]);    \n  }\n  \n  int merge(int x, int y) {\n    int rx = find(x);\n    int ry = find(y);\n    if (rx == ry) return 1;\n    p_[rx] = ry;\n    ++e_;\n    return 0;\n  }  \n  \n  int edges() const { return e_; }\nprivate:\n  vector<int> p_;\n  int e_;\n};\n\nclass Solution {\npublic:\n  int maxNumEdgesToRemove(int n, vector<vector<int>>& edges) {\n    int ans = 0;\n    DSU A(n), B(n);\n    for (const auto& e: edges) {\n      if (e[0] != 3) continue;\n      ans += A.merge(e[1], e[2]);\n      B.merge(e[1], e[2]);\n    }\n    for (const auto& e: edges) {\n      if (e[0] == 3) continue;\n      DSU& d = e[0] == 1 ? A : B;\n      ans += d.merge(e[1], e[2]);\n    }\n    return (A.edges() == n - 1 && B.edges() == n - 1) ? ans : -1;\n  }\n};\n<\/pre>\n\n<\/div><h2 class=\"tabtitle\">python3<\/h2>\n<div class=\"tabcontent\">\n\n<pre lang=\"python\">\nclass DSU:\n  def __init__(self, n: int):\n    self.p = list(range(n))\n    self.e = 0\n    \n  def find(self, x: int) -> int:\n    if x != self.p[x]: self.p[x] = self.find(self.p[x])\n    return self.p[x]\n  \n  def merge(self, x: int, y: int) -> int:\n    rx, ry = self.find(x), self.find(y)\n    if rx == ry: return 1\n    self.p[rx] = ry\n    self.e += 1\n    return 0\n  \nclass Solution:\n  def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:\n    A, B = DSU(n + 1), DSU(n + 1)    \n    ans = 0\n    for t, x, y in edges:\n      if t != 3: continue\n      ans += A.merge(x, y)\n      B.merge(x, y)\n    for t, x, y in edges:\n      if t == 3: continue\n      d = A if t == 1 else B\n      ans += d.merge(x, y)\n    return ans if A.e == B.e == n - 1 else -1\n<\/pre>\n<\/div><\/div>\n","protected":false},"excerpt":{"rendered":"<p>Alice and Bob have an undirected graph of&nbsp;n&nbsp;nodes&nbsp;and 3 types of edges: Type 1: Can be traversed by Alice only. Type 2: Can be traversed&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[76],"tags":[77,217,648,113],"class_list":["post-7354","post","type-post","status-publish","format-standard","hentry","category-graph","tag-graph","tag-hard","tag-spanning-tree","tag-union-find","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/7354","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=7354"}],"version-history":[{"count":3,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/7354\/revisions"}],"predecessor-version":[{"id":7358,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/7354\/revisions\/7358"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=7354"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=7354"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=7354"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}