![](/img/trans.png)
[英]Given a tree, find the kth node in the path from node 'a' to node 'b' in Log(n)?
[英]Check if a node is present in Path from A to B in tree
会有很多查询。 每次查询(A,B,K)都需要你检查从A到B的路径中是否可以找到一个节点(value=K)。解预计不超过O(n+qlogq),n,q: node计数,查询计数。
我心里有个解决办法。 我把它贴下来。 我想知道其他方法是什么。
我的方法:
查找 A 和 B 之间的 LCA(最低共同祖先)。检查 K 是否是 A 或 B 的祖先。如果是=> 检查 LCA 是否是 K 的祖先。如果是,output 是。 要确定一个顶点是否是另一个顶点的祖先,我们可以检查一个顶点是否存在于另一个顶点的子树中。 (如果我们在 dfs 中预处理节点的进出访问顺序,这可以在 O(1) 中完成。https://www.geeksforgeeks.org/printing-pre-and-post-visited-times-in-dfs-of- a-图/ )
但是如果所有查询都具有相同的 K 值,则复杂性会增加。 我们需要检查所有满足 A 或 B 进出时间的 K。因此,为了优化,我们可以将所有 K 分别与 DFS 的进出时间排序。
有什么想法吗?
R存在于U和V之间的路径有以下几种情况:
// Function that return true if R
// exists on the path between U
// and V in the given tree
bool isPresent(int U, int V, int R)
{
// Calculating LCA between U and V
int LCA = lowestCommonAncestor(U, V);
// Calculating LCA between U and R
int LCA_1 = lowestCommonAncestor(U, R);
// Calculating LCA between U and V
int LCA_2 = lowestCommonAncestor(V, R);
if (LCA == R || (LCA_1 == LCA && LCA_2 == R) ||
(LCA_2 == LCA && LCA_1 == R)) {
return true;
}
return false;
}
查找 A 和 B 之间的 LCA(最低共同祖先)。检查 K 是否是 A 或 B 的父级。如果是=> 检查 LCA 是否是 K 的父级。如果是,output 是。 要确定一个顶点是否是另一个顶点的父顶点,我们可以检查一个顶点是否存在于另一个顶点的子树中。 (如果我们在 dfs 中预处理节点的进出访问顺序,这可以在 O(1) 中完成。https://www.geeksforgeeks.org/printing-pre-and-post-visited-times-in-dfs-of- a-图/ )
但是如果所有查询都具有相同的 K 值,则复杂性会增加。 我们需要检查所有满足 A 或 B 进出时间的 K。因此,为了优化,我们可以将所有 K 分别与 DFS 的进出时间排序。
有什么想法吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.