{"id":34318,"date":"2024-11-01T09:26:46","date_gmt":"2024-11-01T09:26:46","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=34318"},"modified":"2024-11-01T10:57:44","modified_gmt":"2024-11-01T10:57:44","slug":"c-coding-test-course-finding-the-lowest-common-ancestor-2-2","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/34318\/","title":{"rendered":"C++ Coding Test Course, Finding the Lowest Common Ancestor 2"},"content":{"rendered":"<p><body><\/p>\n<h2>Problem Description<\/h2>\n<p>There is a tree consisting of N nodes and N-1 edges. Each node is numbered from 1 to N. Given two nodes A and B, the task is to find the Lowest Common Ancestor (LCA) of these two nodes. However, since the tree can be very large, an efficient algorithm needs to be used.<\/p>\n<h3>Input<\/h3>\n<ul>\n<li>The first line contains the number of nodes N (1 \u2264 N \u2264 100,000).<\/li>\n<li>The second line provides the N-1 edge information. Each edge is given in the form of &#8220;parent child.&#8221;<\/li>\n<li>The third line consists of the number of queries Q (1 \u2264 Q \u2264 100,000) for which A and B are given.<\/li>\n<\/ul>\n<h2>Example Input<\/h2>\n<pre>\n7\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7\n4 5\n3\n4 5\n4 6\n5 6\n<\/pre>\n<h2>Example Output<\/h2>\n<pre>\n2\n1\n3\n<\/pre>\n<h2>Solution Strategy<\/h2>\n<p>To efficiently find the Lowest Common Ancestor, we will use the following approach.<\/p>\n<ul>\n<li><strong>Representation of Tree Structure:<\/strong> The tree is represented using an adjacency list. Each node is connected to its parent and children, thus forming the tree.<\/li>\n<li><strong>Creating Depth and Parent Arrays using DFS:<\/strong> We use the Depth First Search (DFS) algorithm to determine the depth of each node and to record the parent nodes. This information is essential for finding the LCA.<\/li>\n<li><strong>Binary Lifting:<\/strong> To efficiently find the LCA, we use the binary lifting method (Fast LCA). The process involves aligning the depths of the two nodes and finding their common ancestor.<\/li>\n<\/ul>\n<h2>Implementation Steps<\/h2>\n<h3>1. Creating Tree Structure<\/h3>\n<p>First, we build the tree based on the edge information. In this process, we define the relationship between parents and children and represent it through an adjacency list.<\/p>\n<h3>2. Generating Depth and Parent Arrays using DFS<\/h3>\n<p>Now, we need to record the depth and parent of each node using DFS. The depth indicates how far each node is from the root, and the parent information is crucial for finding the LCA in the next step.<\/p>\n<h3>3. Implementing LCA Function<\/h3>\n<p>We implement a function to find the Lowest Common Ancestor of two nodes using binary lifting. This function compares the depths of the two nodes and adjusts the depths if needed, subsequently finding their ancestors.<\/p>\n<h3>4. Processing Queries<\/h3>\n<p>For each query, we find and output the LCA of the given two nodes A and B.<\/p>\n<h2>Code Implementation<\/h2>\n<pre>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nconst int MAX_N = 100000;\nconst int LOG = 17; \/\/ log2(100000) \u2248 16.61\n\nint parent[MAX_N + 1][LOG + 1]; \/\/ Parent array\nint depth[MAX_N + 1];            \/\/ Depth array\nvector<int> tree[MAX_N + 1];     \/\/ Tree in adjacency list format\nint N;\n\nvoid dfs(int node, int par, int d) {\n    depth[node] = d;\n    parent[node][0] = par;\n    for (int i = 1; i <= LOG; i++) {\n        parent[node][i] = parent[parent[node][i - 1]][i - 1];\n    }\n    \n    for (int child : tree[node]) {\n        if (child != par) {\n            dfs(child, node, d + 1);\n        }\n    }\n}\n\nint lca(int a, int b) {\n    if (depth[a] < depth[b]) swap(a, b);\n\n    for (int i = LOG; i >= 0; i--) {\n        if (depth[parent[a][i]] >= depth[b]) {\n            a = parent[a][i];\n        }\n    }\n\n    if (a == b) return a;\n\n    for (int i = LOG; i >= 0; i--) {\n        if (parent[a][i] != parent[b][i]) {\n            a = parent[a][i];\n            b = parent[b][i];\n        }\n    }\n\n    return parent[a][0];\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N;\n    for (int i = 0; i < N - 1; i++) {\n        int u, v;\n        cin >> u >> v;\n        tree[u].push_back(v);\n        tree[v].push_back(u);\n    }\n\n    dfs(1, 0, 0); \/\/ Root is 1\n    int Q;\n    cin >> Q;\n\n    for (int i = 0; i < Q; i++) {\n        int a, b;\n        cin >> a >> b;\n        cout << lca(a, b) << '\\n';\n    }\n\n    return 0;\n}\n<\/int><\/cmath><\/algorithm><\/vector><\/iostream><\/pre>\n<h2>Conclusion<\/h2>\n<p>This problem helps understand the use of DFS and binary lifting methods to find the Lowest Common Ancestor. Learning various algorithms to process trees and enhancing coding skills will be greatly beneficial. Practicing different approaches to explore tree structures and find the LCA based on the given problem will be very useful for coding test preparation.<\/p>\n<p><\/body><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Problem Description There is a tree consisting of N nodes and N-1 edges. Each node is numbered from 1 to N. Given two nodes A and B, the task is to find the Lowest Common Ancestor (LCA) of these two nodes. However, since the tree can be very large, an efficient algorithm needs to be &hellip; <a href=\"https:\/\/atmokpo.com\/w\/34318\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;C++ Coding Test Course, Finding the Lowest Common Ancestor 2&#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-34318","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, Finding the Lowest Common Ancestor 2 - \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\/34318\/\" \/>\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, Finding the Lowest Common Ancestor 2 - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"Problem Description There is a tree consisting of N nodes and N-1 edges. Each node is numbered from 1 to N. Given two nodes A and B, the task is to find the Lowest Common Ancestor (LCA) of these two nodes. However, since the tree can be very large, an efficient algorithm needs to be &hellip; \ub354 \ubcf4\uae30 &quot;C++ Coding Test Course, Finding the Lowest Common Ancestor 2&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/34318\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:26:46+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T10:57:44+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\/34318\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34318\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"C++ Coding Test Course, Finding the Lowest Common Ancestor 2\",\"datePublished\":\"2024-11-01T09:26:46+00:00\",\"dateModified\":\"2024-11-01T10:57:44+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34318\/\"},\"wordCount\":416,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"C++ Coding Test Tutorials\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/34318\/\",\"url\":\"https:\/\/atmokpo.com\/w\/34318\/\",\"name\":\"C++ Coding Test Course, Finding the Lowest Common Ancestor 2 - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:26:46+00:00\",\"dateModified\":\"2024-11-01T10:57:44+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34318\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/34318\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/34318\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"C++ Coding Test Course, Finding the Lowest Common Ancestor 2\"}]},{\"@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, Finding the Lowest Common Ancestor 2 - \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\/34318\/","og_locale":"ko_KR","og_type":"article","og_title":"C++ Coding Test Course, Finding the Lowest Common Ancestor 2 - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"Problem Description There is a tree consisting of N nodes and N-1 edges. Each node is numbered from 1 to N. Given two nodes A and B, the task is to find the Lowest Common Ancestor (LCA) of these two nodes. However, since the tree can be very large, an efficient algorithm needs to be &hellip; \ub354 \ubcf4\uae30 \"C++ Coding Test Course, Finding the Lowest Common Ancestor 2\"","og_url":"https:\/\/atmokpo.com\/w\/34318\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:26:46+00:00","article_modified_time":"2024-11-01T10:57:44+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\/34318\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/34318\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"C++ Coding Test Course, Finding the Lowest Common Ancestor 2","datePublished":"2024-11-01T09:26:46+00:00","dateModified":"2024-11-01T10:57:44+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/34318\/"},"wordCount":416,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["C++ Coding Test Tutorials"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/34318\/","url":"https:\/\/atmokpo.com\/w\/34318\/","name":"C++ Coding Test Course, Finding the Lowest Common Ancestor 2 - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:26:46+00:00","dateModified":"2024-11-01T10:57:44+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/34318\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/34318\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/34318\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"C++ Coding Test Course, Finding the Lowest Common Ancestor 2"}]},{"@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\/34318","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=34318"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/34318\/revisions"}],"predecessor-version":[{"id":34319,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/34318\/revisions\/34319"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=34318"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=34318"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=34318"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}