三种LCA算法(三):转化为LCA问题(dfs+ST表实现)
来源:互联网 发布:儿童故事书软件 编辑:程序博客网 时间:2024/05/16 05:09
转化为RMQ问题也是比较常用的LCA算法之一,大多采用dfs+ST表实现,在线算法,复杂度为O(n + nlogn + Q),Q为查询次数。在线算法里,dfs+ST表算法比Doubly算法快。
算法流程:
1.对树进行dfs,将遍历到的节点按照顺序记下,将得到一个长度为2*n - 1的序列。
2.每个节点都在序列中出现,我们记录节点u第一次在序列中出现的位置为first[u]。
3.根据dfs的性质,对于两节点u、v,从first[u]遍历到first[v]的过程会经过LCA(u,v),他的深度是从min(first[u],first[v])到max(first[u],first[v])序列中最小的。
代码:
#include <cstdio>#include <cstring>#include <algorithm>#include <iostream>using namespace std;int n;//前向星存树int cnt, head[1005];struct edges {int to, next;}edge[2010];//遍历信息int tot, path[2010], depth[2010], first[1005];//path:遍历路径 depth:路径上的点的深度 first:节点在路经中首先出现的位置//ST表信息int dp[2010][15], upper[2010];void add(int x, int y) {//树加边cnt++;edge[cnt].to = y;edge[cnt].next = head[x];head[x] = cnt;}void dfs(int x, int fa, int dep) {path[++tot] = x; depth[tot] = dep, first[x] = x;for (int i = head[x]; i; i = edge[i].next) {int y = edge[i].to;if (y != x) {dfs(y, x, dep + 1);path[++tot] = x;depth[tot] = dep;}}}void init() {//ST表相关准备upper[0] = -1;for (int i = 1; i < 2010; i++) {upper[i] = i &(i - 1) == 0 ? upper[i - 1] + 1 : upper[i - 1];}}void ST() {//建ST表int k = upper[tot + 1];for (int i = 0; i <= tot; i++) {dp[i][0] = i;}for (int i = 1; i <= k; i++) {for (int j = 0;j + (1 << i) - 1 <= tot; j++) {int a = dp[j][i - 1];int b = dp[j + (1 << (i - 1))][i - 1];dp[j][i] = depth[a] < depth[b] ? a : b;}}}int rmq(int le, int rig) {//转化为rmq问题int k = upper[rig - le + 1];int a = dp[le][k];int b = dp[rig - (1 << k) + 1][k];return depth[a] < depth[b] ? a : b;}int lca(int x, int y) {//lca问题x = first[x];y = first[y];if (x > y) swap(x, y);return path[rmq(x, y)];}int main() {int Q;int a, b;init();while (scanf("%d%d", &n, &Q) != EOF) {cnt = 0;memset(head, 0, sizeof(head));for (int i = 0; i < n - 1; i++) {scanf("%d%d", &a, &b);add(a, b);add(b, a);}tot = -1;dfs(0, -1, 0);//假设0为树根ST();for (int i = 0; i < Q; i++) {scanf("%d%d", &a, &b);printf("%d\n", lca(a, b));}}return 0;}
阅读全文
1 0
- 三种LCA算法(三):转化为LCA问题(dfs+ST表实现)
- LCA(st算法)
- LCA转化RMQ(内附RMQ算法ST)
- LCA(dfs+st)在线算法
- Gym 100512D Dynamic LCA ((LCA 在线算法DFS+ST) + 分类讨论!!)
- LCA问题(含RMQ的ST算法)
- 最近公共祖先(LCA)问题-在线ST算法
- 三种LCA算法(二):Tarjan算法
- [CF 191C]Fools and Roads[LCA Tarjan算法][LCA 与 RMQ问题的转化][LCA ST算法]
- hdu2586 LCA入门(在线算法ST)
- lca的ST算法(在线)
- LCA在线算法ST&&DFS->POJ1330&&POJ1470
- [POJ]1330 Nearest Common Ancestors (LCA,DFS+ST在线算法 || 倍增算法 || Tarjan离线算法)
- SOJ-1008(将LCA问题转化为RMQ)
- 最近公共祖先LCA(Tarjan与DFS--ST倍增)
- 普通RMQ问题转化为LCA问题的算法
- LCA-ST算法&Tarjan_LCA
- ST算法与LCA
- 【Ubuntu】/mnt/hgfs 权限不够的替代方法
- eclipse新建maven项目,修改默认jdk版本
- 从代码层面优化系统性能应该怎么做?(上)
- 【HDU6040】Hints of sd0061(nth_element)
- TCP之三次握手和四次挥手
- 三种LCA算法(三):转化为LCA问题(dfs+ST表实现)
- Linux关机命令总结
- 电脑windows系统动态壁纸装X器wallpaper engine下载资源和使用教程
- 系统相关功能开发(三)-系统控制与调用
- Android PriorityQueue和PriorityBlockingQueue源码解析
- 关于cocoapods的一些东西
- 你和美女就差一个双眼皮的距离
- oracle缺失表达,多数情况下是因为select的最后一个有逗号
- 结构类型