{"id":34274,"date":"2024-11-01T09:26:16","date_gmt":"2024-11-01T09:26:16","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=34274"},"modified":"2024-11-01T10:57:54","modified_gmt":"2024-11-01T10:57:54","slug":"c-coding-test-course-union-find-2","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/34274\/","title":{"rendered":"C++ Coding Test Course, Union Find"},"content":{"rendered":"<p><body><\/p>\n<p>The Union-Find data structure is very useful for solving algorithmic problems. In this article, we will explain the concept of Union-Find and detail the problem-solving process using C++.<\/p>\n<h2>What is Union-Find?<\/h2>\n<p>The Union-Find algorithm is a data structure that efficiently manages a collection of data. This data structure is also known as Disjoint Set and primarily supports the following two operations:<\/p>\n<ul>\n<li><strong>Find:<\/strong> This operation finds which set a particular element belongs to. It returns the representative element (root node) of the set.<\/li>\n<li><strong>Union:<\/strong> This operation merges two sets. It connects the root nodes of the two sets to form one set.<\/li>\n<\/ul>\n<p>It is mainly used to find cycles in graph theory or to check connected components. There are two optimization techniques to effectively utilize Union-Find:<\/p>\n<h3>1. Path Compression<\/h3>\n<p>When performing the Find operation, it updates the parent of all nodes along the path to the root node, allowing for faster retrieval of the root node in subsequent operations.<\/p>\n<h3>2. Rank-based Union<\/h3>\n<p>When performing the Union operation, it compares the sizes of two sets and connects the smaller set as a child of the larger set. This helps to reduce the height of the tree.<\/p>\n<h2>Problem Description<\/h2>\n<p>Now, let&#8217;s look at a problem that can be solved using the Union-Find algorithm. We will solve the problem below.<\/p>\n<h3>Problem: Friend Network<\/h3>\n<p>There is a friend network in which several friends are connected to each other. Each friend is identified by a number from 1 to N. Two friends are considered friends if they are directly or indirectly connected. Given a pair of friends (a, b), check whether a and b belong to the same friend group in the friend network.<\/p>\n<h4>Input Format<\/h4>\n<ul>\n<li>The first line contains the number of friends N and the number of friend relationships M. (1 \u2264 N \u2264 100,000, 1 \u2264 M \u2264 100,000)<\/li>\n<li>From the second line onward, M pairs of friend relationships a, b are given.<\/li>\n<li>The last line contains the query Q, where each query provides a pair of friends (x, y).<\/li>\n<\/ul>\n<h4>Output Format<\/h4>\n<p>For each query, print &#8216;YES&#8217; if x and y belong to the same friend group, otherwise print &#8216;NO&#8217;.<\/p>\n<h2>Algorithm Approach<\/h2>\n<ol>\n<li>Initialize and connect the friend relationships using Union-Find. Use <code>Union(a, b)<\/code> to connect a and b in the same set.<\/li>\n<li>For each query, use <code>Find(x)<\/code> and <code>Find(y)<\/code> to check the root nodes of the two friends. If they have the same root node, print &#8216;YES&#8217;; otherwise, print &#8216;NO&#8217;.<\/li>\n<\/ol>\n<h2>C++ Code Implementation<\/h2>\n<p>Below is the C++ code that implements the Union-Find algorithm:<\/p>\n<pre><code>\n#include <iostream>\n#include <vector>\nusing namespace std;\n\nclass UnionFind {\npublic:\n    UnionFind(int n) {\n        parent.resize(n);\n        rank.resize(n, 0);\n        for (int i = 0; i < n; ++i) {\n            parent[i] = i;\n        }\n    }\n\n    int find(int x) {\n        if (parent[x] != x) {\n            parent[x] = find(parent[x]); \/\/ Path compression\n        }\n        return parent[x];\n    }\n\n    void unionSets(int x, int y) {\n        int rootX = find(x);\n        int rootY = find(y);\n\n        if (rootX != rootY) {\n            \/\/ Rank-based union\n            if (rank[rootX] > rank[rootY]) {\n                parent[rootY] = rootX;\n            } else if (rank[rootX] < rank[rootY]) {\n                parent[rootX] = rootY;\n            } else {\n                parent[rootY] = rootX;\n                rank[rootX]++;\n            }\n        }\n    }\n\nprivate:\n    vector<int> parent;\n    vector<int> rank;\n};\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    UnionFind uf(N + 1);\n\n    for (int i = 0; i < M; i++) {\n        int a, b;\n        cin >> a >> b;\n        uf.unionSets(a, b);\n    }\n\n    int Q;\n    cin >> Q;\n    for (int i = 0; i < Q; i++) {\n        int x, y;\n        cin >> x >> y;\n        if (uf.find(x) == uf.find(y)) {\n            cout << \"YES\" << endl;\n        } else {\n            cout << \"NO\" << endl;\n        }\n    }\n\n    return 0;\n}\n<\/code><\/pre>\n<h2>Code Explanation<\/h2>\n<p>In the above C++ code, we implemented the following components:<\/p>\n<ul>\n<li><strong>UnionFind class:<\/strong> Contains the main logic of the Union-Find algorithm. The <code>find<\/code> function finds the root node, and the <code>unionSets<\/code> function merges two sets.<\/li>\n<li><strong>Main function:<\/strong> Takes the friend relationships as input, stores them in the Union-Find structure, and outputs the results for the given queries.<\/li>\n<\/ul>\n<h2>Time Complexity<\/h2>\n<p>The time complexity of the Union-Find algorithm is as follows:<\/p>\n<ul>\n<li>Find operation: Almost constant time (\u03b1(N), proportional to the inverse Ackermann function)<\/li>\n<li>Union operation: Almost constant time<\/li>\n<\/ul>\n<p>Thus, the overall time complexity of the algorithm is O(M * \u03b1(N)), where M is the number of friend relationships.<\/p>\n<h2>Conclusion<\/h2>\n<p>In this course, we have examined the concept of the Union-Find data structure and the problem-solving process using C++ in detail. Union-Find is a powerful tool that can be effectively utilized in various problems. I hope it will be of great help in your future coding tests.<\/p>\n<p><\/body><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The Union-Find data structure is very useful for solving algorithmic problems. In this article, we will explain the concept of Union-Find and detail the problem-solving process using C++. What is Union-Find? The Union-Find algorithm is a data structure that efficiently manages a collection of data. This data structure is also known as Disjoint Set and &hellip; <a href=\"https:\/\/atmokpo.com\/w\/34274\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;C++ Coding Test Course, Union Find&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[111],"tags":[],"class_list":["post-34274","post","type-post","status-publish","format-standard","hentry","category-c-coding-test-tutorials-2"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>C++ Coding Test Course, Union Find - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/atmokpo.com\/w\/34274\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"C++ Coding Test Course, Union Find - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"The Union-Find data structure is very useful for solving algorithmic problems. In this article, we will explain the concept of Union-Find and detail the problem-solving process using C++. What is Union-Find? The Union-Find algorithm is a data structure that efficiently manages a collection of data. This data structure is also known as Disjoint Set and &hellip; \ub354 \ubcf4\uae30 &quot;C++ Coding Test Course, Union Find&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/34274\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:26:16+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T10:57:54+00:00\" \/>\n<meta name=\"author\" content=\"root\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:site\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:label1\" content=\"\uae00\uc4f4\uc774\" \/>\n\t<meta name=\"twitter:data1\" content=\"root\" \/>\n\t<meta name=\"twitter:label2\" content=\"\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04\" \/>\n\t<meta name=\"twitter:data2\" content=\"3\ubd84\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/atmokpo.com\/w\/34274\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34274\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"C++ Coding Test Course, Union Find\",\"datePublished\":\"2024-11-01T09:26:16+00:00\",\"dateModified\":\"2024-11-01T10:57:54+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34274\/\"},\"wordCount\":565,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"C++ Coding Test Tutorials\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/34274\/\",\"url\":\"https:\/\/atmokpo.com\/w\/34274\/\",\"name\":\"C++ Coding Test Course, Union Find - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:26:16+00:00\",\"dateModified\":\"2024-11-01T10:57:54+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34274\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/34274\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/34274\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"C++ Coding Test Course, Union Find\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/atmokpo.com\/w\/#website\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/atmokpo.com\/w\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"ko-KR\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"contentUrl\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"width\":400,\"height\":400,\"caption\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\"},\"image\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/bebubo4\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\",\"name\":\"root\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"caption\":\"root\"},\"sameAs\":[\"http:\/\/atmokpo.com\/w\"],\"url\":\"https:\/\/atmokpo.com\/w\/author\/root\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"C++ Coding Test Course, Union Find - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/atmokpo.com\/w\/34274\/","og_locale":"ko_KR","og_type":"article","og_title":"C++ Coding Test Course, Union Find - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"The Union-Find data structure is very useful for solving algorithmic problems. In this article, we will explain the concept of Union-Find and detail the problem-solving process using C++. What is Union-Find? The Union-Find algorithm is a data structure that efficiently manages a collection of data. This data structure is also known as Disjoint Set and &hellip; \ub354 \ubcf4\uae30 \"C++ Coding Test Course, Union Find\"","og_url":"https:\/\/atmokpo.com\/w\/34274\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:26:16+00:00","article_modified_time":"2024-11-01T10:57:54+00:00","author":"root","twitter_card":"summary_large_image","twitter_creator":"@bebubo4","twitter_site":"@bebubo4","twitter_misc":{"\uae00\uc4f4\uc774":"root","\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04":"3\ubd84"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/atmokpo.com\/w\/34274\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/34274\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"C++ Coding Test Course, Union Find","datePublished":"2024-11-01T09:26:16+00:00","dateModified":"2024-11-01T10:57:54+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/34274\/"},"wordCount":565,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["C++ Coding Test Tutorials"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/34274\/","url":"https:\/\/atmokpo.com\/w\/34274\/","name":"C++ Coding Test Course, Union Find - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:26:16+00:00","dateModified":"2024-11-01T10:57:54+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/34274\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/34274\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/34274\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"C++ Coding Test Course, Union Find"}]},{"@type":"WebSite","@id":"https:\/\/atmokpo.com\/w\/#website","url":"https:\/\/atmokpo.com\/w\/","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","description":"","publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/atmokpo.com\/w\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"ko-KR"},{"@type":"Organization","@id":"https:\/\/atmokpo.com\/w\/#organization","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","url":"https:\/\/atmokpo.com\/w\/","logo":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/","url":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","contentUrl":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","width":400,"height":400,"caption":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8"},"image":{"@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/bebubo4"]},{"@type":"Person","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7","name":"root","image":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","caption":"root"},"sameAs":["http:\/\/atmokpo.com\/w"],"url":"https:\/\/atmokpo.com\/w\/author\/root\/"}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/34274","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/comments?post=34274"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/34274\/revisions"}],"predecessor-version":[{"id":34275,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/34274\/revisions\/34275"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=34274"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=34274"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=34274"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}