{"id":263,"date":"2026-11-13T12:36:18","date_gmt":"2026-11-13T04:36:18","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-tarjan-answers-lca-queries-offline\/"},"modified":"2026-11-13T21:53:58","modified_gmt":"2026-11-13T13:53:58","slug":"how-tarjan-answers-lca-queries-offline","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-tarjan-answers-lca-queries-offline\/","title":{"rendered":"How Tarjan answers LCA queries offline"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Tarjan&#8217;s offline LCA<\/strong> answers a batch of lowest-common-ancestor queries during one depth-first search, using <strong>union-find<\/strong>. When the search finishes a node, the node is united with its parent and the parent&#8217;s set is labeled with the parent. A query between the finished node and a node already visited is answered by the label of that visited node&#8217;s set. The time is <strong>O(n + q \u00b7 \u03b1(n))<\/strong> for q queries. The queries must be known before the search starts.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Binary lifting spends O(n log n) preprocessing even if only a few queries arrive later, and it answers them online. A batch that is known in advance can be answered in essentially linear time. The depth-first search visits each edge a constant number of times. The missing ingredient is a way to name, for a node already finished, the highest ancestor that has not finished. Union-find with an ancestor label stores exactly that.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The algorithm is offline. A query that arrives after the search has finished is not answered by another lookup in the same structure. The batch is the input.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Every query pair is reported once, when the later of the two nodes finishes, and the reported ancestor is the LCA. Time is the depth-first search plus a union and a find per tree edge and per query, which is O(n + q \u03b1(n)) with path compression and union by rank. Extra memory is the union-find arrays and the list of queries incident to each node.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The union happens after the node&#8217;s children are processed, and the set&#8217;s ancestor pointer is then set to the node&#8217;s parent. Uniting before the subtree finishes, or labeling the set with the node instead of the parent at the wrong moment, answers with a descendant. The usual presentation unites a finished node to its parent and sets find-root&#8217;s ancestor to the parent.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>Attach each query to both of its endpoints, so either endpoint can see the pair.<\/li>\n<li>Run a depth-first search. On entering a node, mark it seen and create a singleton set whose ancestor label is itself.<\/li>\n<li>Recurse into each child. When a child returns, union the child with the current node and set the ancestor label of the merged set to the current node.<\/li>\n<li>After the children, scan the queries stored at this node. If the other endpoint is already seen, the answer is the ancestor label of that endpoint&#8217;s set.<\/li>\n<li>The other endpoint will not answer the same query again if each query is emitted only when the second endpoint is processed. Tie the emission to a check that the other side is already seen.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The nearly linear bound is for a static tree and a fixed batch. Online queries belong to binary lifting or to an Euler-tour sparse table. The union-find here does not maintain a spanning forest under insertions. Calling this procedure Tarjan&#8217;s strongly connected components is a different algorithm that shares an author and a stack-free confusion. This one is the LCA batch.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when a query is answered before both nodes are seen<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Answer a query on entering the first endpoint<\/td>\n<td>The other endpoint may be unvisited, and the union-find has not built the ancestor chain between them. The answer is emitted when the second endpoint is seen.<\/td>\n<\/tr>\n<tr>\n<td>Forget to relabel the set with the current node after uniting a child<\/td>\n<td>The find root would still name the child. The LCA would come back as a descendant of the true answer.<\/td>\n<\/tr>\n<tr>\n<td>Accept a new query after the search and call find<\/td>\n<td>The ancestor labels were correct only at the moment the second endpoint finished. The structure is not an online oracle.<\/td>\n<\/tr>\n<tr>\n<td>Use this timing for strongly connected components<\/td>\n<td>Strong components use a low-link stack on a directed graph. The union-find in this algorithm tracks unfinished ancestors in a tree.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">Online LCA belongs to binary lifting or an Euler tour with a range-minimum query. Strongly connected components belong to Tarjan&#8217;s other one-pass algorithm or to Kosaraju. This procedure is the offline batch.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">This Python fragment unions each finished child into the current node and labels the set with that node. A query is answered when its other endpoint is already seen. On the tree with root 0 and queries (3, 4), (3, 2), (4, 1) the answers are <code>1 0 1<\/code>.<\/p>\n\n<pre><code class=\"language-python\">children = [[1, 2], [3, 4], [], [], []]\nqueries = [(3, 4), (3, 2), (4, 1)]\nattached = [[] for _ in range(5)]\nfor index, (a, b) in enumerate(queries):\n    attached[a].append((b, index))\n    attached[b].append((a, index))\nparent = list(range(5))\nancestor = list(range(5))\nseen = [False] * 5\nanswer = [None] * len(queries)\n\ndef find(x):\n    if parent[x] != x:\n        parent[x] = find(parent[x])\n    return parent[x]\n\ndef dfs(u):\n    seen[u] = True\n    for v in children[u]:\n        dfs(v)\n        parent[find(v)] = u\n        ancestor[u] = u\n    for other, index in attached[u]:\n        if seen[other] and answer[index] is None:\n            answer[index] = ancestor[find(other)]\n\ndfs(0)\nassert answer == [1, 0, 1]\nprint(*answer)\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Tarjan&#8217;s offline LCA answers a batch of deepest-common-ancestor questions once the tree and every query are known. A compiler or a directory tool that can wait for the whole batch can use it. Binary lifting answers the same question online.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Drop the offline pass when queries arrive interleaved with the answers, or when the tree is not static. Use binary lifting. Keep Tarjan&#8217;s offline LCA when the whole batch is known and the nearly linear bound matters.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for Tarjan&#8217;s offline LCA returns the union-find labeling during depth-first search and the requirement that the batch is known first. <strong>Tarjan&#8217;s offline algorithm answers a batch of LCA queries in almost linear time by labeling union-find sets with ancestors during one depth-first search.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Short answer: Tarjan&#8217;s offline LCA answers a batch of lowest-common-ancestor queries during one depth-first search, using union-find. When the search finishes a node, the node is united with its parent and the parent&#8217;s set is labeled with the parent. A query between the finished node and a node already&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,34],"tags":[],"class_list":["post-263","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-trees"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/263","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=263"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/263\/revisions"}],"predecessor-version":[{"id":662,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/263\/revisions\/662"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=263"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=263"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=263"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}