简体   繁体   English

给定一棵树,在Log(n)中找到从节点“ a”到节点“ b”的路径中的第k个节点?

[英]Given a tree, find the kth node in the path from node 'a' to node 'b' in Log(n)?

Given a tree, I need to find the 'k'th node in the path from 'a' to 'b'. 给定一棵树,我需要在从“ a”到“ b”的路径中找到第k个节点。 That means that I need to find the node at the 'kth' position in the path from node 'a' to node 'b'. 这意味着我需要在从节点“ a”到节点“ b”的路径中的“ kth”位置找到该节点。 I was thinking on the lines of Lowest-common-ancestor and/or heavy-light decomposition but I'm not sure if that's the way to do it. 我在考虑最低共同祖先和/或强光分解的路线,但是我不确定这是否是这样做的方式。 Any guidance in the right direction is appreciated. 朝着正确方向的任何指导表示赞赏。

Details: 细节:

  • The tree is NOT a binary tree. 该树不是二叉树。 It's an undirected graph having n-1 edges, n vertices and no cycles. 它是具有n-1个边,n个顶点且没有循环的无向图。 Just your regular tree 只是你的常规树
  • The tree has vertices numbered from 1 to n. 树的顶点编号为1到n。 There are n-1 undirected edges connecting n-1 pairs of these vertices 有n-1个无向边连接n-1对这些顶点
  • 'a' and 'b' are any 2 vertices numbered from 1 to n in the tree. “ a”和“ b”是树中从1到n编号的任意2个顶点。 We are to find the 'k'th node in the path from 'a' to 'b'. 我们将在从“ a”到“ b”的路径中找到第k个节点。 It is guaranteed that the value of 'k' is <= number of nodes in the path from 'a' to 'b' 保证'k'的值<=从'a'到'b'的路径中的节点数

A BFS applied on every query (kth node from 'a' to 'b') is not an option as the number of queries are large. 由于查询数量很大,因此无法选择将BFS应用于每个查询(从“ a”到“ b”的第k个节点)。

Do the lowest-common-ancestor, and keep for every node it's depth (distance to the root). 做最普通的祖先,并为每个节点保留其深度(到根的距离)。

Next figure out if the k'th node is on the a to lca or lca to b part. 接下来找出第k个节点在a到lca还是lca到b部分。 The difference in depth is the number of nodes between them, so if depth[a] - depth[lca] > k then the node is on lca-b part. 深度差是它们之间节点的数量,因此,如果depth[a] - depth[lca] > k则该节点位于lca-b部分。

If the node is on the a to lca part, just find the k'th ancestor of a. 如果节点在a到lca部分,则只需找到a的第k个祖先。 Should be log(N) using the LCA data you precalculated. 应该使用您预先计算的LCA数据为log(N)。

If the node is on the b to lca part, then you can compute k' which is the distance of the kth node from b ( k' = 1 + depth[a] + depth[b] - 2*depth[lca] - k) ) and then get k' ancestor of b (again easy with the the LCA data). 如果该节点位于b到lca部分,则可以计算k',它是第k个节点到b的距离( k' = 1 + depth[a] + depth[b] - 2*depth[lca] - k) ),然后获得b的k'祖先(同样很容易获得LCA数据)。

Overall all the lookups are logN and the other steps are constant so you do O(LogN) per query. 总体而言,所有查找都是logN,其他步骤是恒定的,因此您对每个查询执行O(LogN)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM