c++ - 在 O(logn) 时间内使用稀疏矩阵的 LCA
问题描述
for (int i=0; i<level; i++)
if ((diff>>i)&1)
v = parent[v][i];
在上面的代码中,当“(diff>>i)”为奇数时,它只跳转到第 2^ith 父级。为什么会这样?我们如何理解只有在奇数“(diff>>i)”的情况下,我们才必须跳转?
解决方案
首先,这个答案没有解释你分享的片段。
我也真的不明白那部分代码。我不确定那里的代码是否存在错误,因为这似乎不正确。我可以在这部分分享我的功能,希望你会发现它更容易理解。我发表了一些评论以方便您的理解。
int lcaQuery(int p, int q) {
if(depth[p] < depth[q]) {
swap(p, q);
}
// uplifting p at the same level/height of q
for(int i = level - 1; i >= 0; i--) {
if (depth[p] - (1 << i) >= depth[q]) {
p = parent[p][i];
}
}
// if already catch q, this is the LCA
if (p == q) return p;
// uplifting p and q until both of their parents are same and we reach the root
for(int i = level - 1; i >= 0; i--) {
if (parent[p][i] != -1 and parent[p][i] != parent[q][i]) {
p = parent[p][i];
q = parent[q][i];
}
}
// since now both p and q are in the same level, return their parent
return parent[p][0];
}
推荐阅读
- marklogic - 使用 Search API 进行跨文档搜索和排序
- wordpress - 创建后在属性中启用存档 (Woocommerce)
- python-3.x - How to move the files from one folder to other folder based on time or date
- javascript - Chrome 和 IE11 中的地图标记图像质量不佳
- android - 显示 Snackbar 时布局会缩小内容
- python - 包含微平均和宏观平均 F1 分数的表
- c# - Is it possible to have two or more active modal windows at the same time?
- javascript - PHP returns whitespace character before anything after AJAX request
- javascript - 如何将 python 语法荧光笔应用于 django 模型 TextField
- configuration-files - 用于自动化属性文件的配置管理工具