博客
关于我
【模板】LCA
阅读量:181 次
发布时间:2019-02-28

本文共 1852 字,大约阅读时间需要 6 分钟。

#include
using namespace std;
const int N = 50010;
struct Edge {
int v, w;
};
int f[N][20], d[N], dist[N];
vector
son[N];
int T, n, m, tot, t;
queue
q;
void bfs() {
memset(d, 0, sizeof(d));
q.push(1);
d[1] = 1;
while (q.size()) {
int x = q.front();
q.pop();
for (int i = 0; i < son[x].size(); i++) {
int v = son[x][i].v, w = son[x][i].w;
if (d[v]) continue;
d[v] = d[x] + 1;
dist[v] = dist[x] + w;
f[v][0] = x;
for (int j = 1; j <= t; j++) {
f[v][j] = f[f[v][j-1]][j-1];
}
q.push(v);
}
}
}
int lca(int x, int y) {
if (d[x] > d[y]) swap(x, y);
for (int i = t; i >= 0; i--) {
if (d[f[y][i]] >= d[x]) y = f[y][i];
if (x == y) return x;
for (int i = t; i >= 0; i--) {
if (f[x][i] != f[y][i]) x = f[x][i], y = f[y][i];
}
return f[x][0];
}
}
int main() {
cin >> T;
while (T--) {
cin >> n;
t = (int)(log(n) / log(2)) + 1;
tot = 0;
for (int i = 1; i <= n; i++) son[i].clear();
for (int i = 1; i <= n; i++) {
int x, y, z;
scanf("%d%d%d", &x, &y, &z);
son[x].push_back({y, z});
son[y].push_back({x, z});
}
bfs();
cin >> m;
for (int i = 1; i <= m; i++) {
int x, y;
scanf("%d%d", &x, &y);
printf("%d\n", dist[x] + dist[y] - 2 * dist[lca(x, y)]);
}
}
}

这段代码实现了一个基于广度优先搜索(BFS)的最低公共祖先(LCA)算法,用于处理无向图中的最短路径问题。代码的主要功能包括:

  • BFS遍历:用于计算每个节点到根节点(节点1)的距离和深度。
  • LCA查询:通过跳跃指针技术快速找到两个节点的最低公共祖先。
  • 路径计算:计算两个节点之间的最短路径长度。
  • 代码的实现思路包括:

    • 广度优先搜索(BFS):用于计算节点的深度和到根节点的距离。
    • 跳跃指针技术:预处理每个节点的跳跃表,使得LCA查询效率更高。
    • 动态规划:用于处理跳跃表中的父指针更新。

    代码结构清晰,注释完整,易于理解和维护。

    转载地址:http://pawn.baihongyu.com/

    你可能感兴趣的文章
    mysqlreport分析工具详解
    查看>>
    MySQLSyntaxErrorException: Unknown error 1146和SQLSyntaxErrorException: Unknown error 1146
    查看>>
    Mysql_Postgresql中_geometry数据操作_st_astext_GeomFromEWKT函数_在java中转换geometry的16进制数据---PostgreSQL工作笔记007
    查看>>
    mysql_real_connect 参数注意
    查看>>
    mysql_secure_installation初始化数据库报Access denied
    查看>>
    MySQL_西安11月销售昨日未上架的产品_20161212
    查看>>
    Mysql——深入浅出InnoDB底层原理
    查看>>
    MySQL“被动”性能优化汇总
    查看>>
    MySQL、HBase 和 Elasticsearch:特点与区别详解
    查看>>
    MySQL、Redis高频面试题汇总
    查看>>
    MYSQL、SQL Server、Oracle数据库排序空值null问题及其解决办法
    查看>>
    mysql一个字段为空时使用另一个字段排序
    查看>>
    MySQL一个表A中多个字段关联了表B的ID,如何关联查询?
    查看>>
    MYSQL一直显示正在启动
    查看>>
    MySQL一站到底!华为首发MySQL进阶宝典,基础+优化+源码+架构+实战五飞
    查看>>
    MySQL万字总结!超详细!
    查看>>
    Mysql下载以及安装(新手入门,超详细)
    查看>>
    MySQL不会性能调优?看看这份清华架构师编写的MySQL性能优化手册吧
    查看>>