How far away ?(LCA)模板

本文介绍了一种求解树状结构中任意两点间最短路径的高效算法。通过深度优先搜索预处理节点深度信息,并利用RMQ算法快速查找最近公共祖先(LCA),进而计算两点间的距离。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

How far away ?

http://acm.hdu.edu.cn/showproblem.php?pid=2586

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 23138    Accepted Submission(s): 9166

Problem Description

There are n houses in the village and some bidirectional roads connecting them. Every day peole always like to ask like this "How far is it if I want to go from house A to house B"? Usually it hard to answer. But luckily int this village the answer is always unique, since the roads are built in the way that there is a unique simple path("simple" means you can't visit a place twice) between every two houses. Yout task is to answer all these curious people.

Input

First line is a single integer T(T<=10), indicating the number of test cases.
  For each test case,in the first line there are two numbers n(2<=n<=40000) and m (1<=m<=200),the number of houses and the number of queries. The following n-1 lines each consisting three numbers i,j,k, separated bu a single space, meaning that there is a road connecting house i and house j,with length k(0<k<=40000).The houses are labeled from 1 to n.
  Next m lines each has distinct integers i and j, you areato answer the distance between house i and house j.

Output

For each test case,output m lines. Each line represents the answer of the query. Output a bland line after each test case.

Sample Input

2

3 2

1 2 10

3 1 15

1 2

2 3

2 2

1 2 100

1 2

2 1

Sample Output

10

25

100

100

Source

ECJTU 2009 Spring Contest

 

 

Recommend

lcy   |   We have carefully selected several similar problems for you:  3486 2888 3234 2818 3038 

裸裸的裸题。就是求一棵树上的两点间的最短距离。

代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn=80000+100;
const int maxm=80000+100;
int cnt,num,head[maxn];
int first[maxn],que[maxn];
int depth[maxn];
int dp[maxn][20];
int dist[maxn];
bool vis[maxn];
struct node{
    int to,next,val;
}G[maxm<<1];
void init(){
    memset(head,-1,sizeof(head));
    memset(vis,false,sizeof(vis));
    cnt=0;
    num=0;
}
void add(int a,int b,int c){
    G[++cnt].to=b;
    G[cnt].val=c;
    G[cnt].next=head[a];
    head[a]=cnt;
}
int dfs(int u,int deep){
    vis[u]=true;///表示是否访问过
    que[++num]=u;///num在此处相当于dfs_clock
    first[u]=num;///表示第一次走的编号
    depth[num]=deep;

    for(int i=head[u];i!=-1;i=G[i].next){
            int v=G[i].to;
            int w=G[i].val;
        if(!vis[v]){
            dist[v]=dist[u]+w;
            dfs(v,deep+1);
            que[++num]=u;
            depth[num]=deep;
        }
    }
}
void ST(int n)
{
    for(int i=1;i<=n;i++)
        dp[i][0] = i;
    for(int j=1;(1<<j)<=n;j++){
        for(int i=1;i+(1<<j)-1<=n;i++){
            int a = dp[i][j-1] , b = dp[i+(1<<(j-1))][j-1];
            dp[i][j] = depth[a]<depth[b]?a:b;
        }
    }
}
//两个节点之间的路径深度最小的就是LCA
int RMQ(int l,int r)
{
    int k=0;
    while((1<<(k+1))<=r-l+1)
        k++;
    int a = dp[l][k], b = dp[r-(1<<k)+1][k]; //保存的是编号
    return depth[a]<depth[b]?a:b;
}
int LCA(int u ,int v)
{
    int x = first[u] , y = first[v];
    if(x > y) swap(x,y);
    int res = RMQ(x,y);
    return que[res];
}

int main()
{
    int t,n,m,a,b,c;
    scanf("%d",&t);
    while(t--){
        init();
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n-1;i++){
            scanf("%d%d%d",&a,&b,&c);
            add(a,b,c);
            add(b,a,c);
        }
        dfs(1,1);
        ST(2*n-1);
        while(m--){
            scanf("%d%d",&a,&b);
            int lca=LCA(a,b);
            ///cout<<"lca:"<<lca<<endl;
            ///cout<<dist[a]<<"   "<<dist[b]<<"  "<<endl;
            printf("%d\n",dist[a]+dist[b]-2*dist[lca]);
        }
    }
    return 0;
}

 

<think>好的,我现在需要帮助用户找到关于LCA(最近公共祖先)算法模板代码和实现示例。首先,我得回忆一下LCA的常见解决方法。常见的算法有暴力法、倍增法、Tarjan算法和树链剖分等。其中,倍增法是比较常用且效率较高的,适合作为模板代码。 用户提到需要模板代码,所以应该优先考虑提供倍增法的实现。倍增法的核心是预处理每个节点的祖先表,然后通过二进制跳跃来快速找到LCA。我需要确保代码结构清晰,注释详细,方便用户理解。 接下来,我需要参考用户提供的引用内容。用户引用了关于Dijkstra算法的时间复杂度、宏定义、SPFA算法以及状态转移方程的内容。虽然这些引用可能与LCA没有直接关系,但引用[4]提到了状态转移方程fa[x][i] = fa[fa[x][i - 1]][i - 1],这正是倍增法中预处理祖先数组的关键步骤。这说明用户可能已经对倍增法的思路有所了解,或者在其他算法中见过类似的结构,这可以帮助他们理解LCA的实现。 因此,我应该重点解释倍增法的步骤,包括预处理和查询两个部分。预处理部分需要为每个节点建立不同层级的祖先信息,而查询部分则需要将两个节点调整到同一深度,然后共同向上跳跃寻找公共祖先。 在代码实现方面,需要定义父数组fa,深度数组depth,以及预处理时的循环结构。比如,用户引用中的宏定义REP可能用于循环,但考虑到用户可能更习惯标准写法,使用普通的for循环更合适。同时,确保代码中的变量命名清晰,比如fa表示父节点,depth表示节点深度。 另外,用户可能关心时间复杂度和适用场景。根据引用[3],Dijkstra在稠密图上是O(n²),而堆优化后是O(mlogn)。同样,倍增法的时间复杂度是预处理O(nlogn)和每次查询O(logn),适合多次查询的情况,这也是需要指出的。 还要注意代码的正确性,比如在预处理时,需要从根节点开始进行DFS或BFS来初始化每个节点的直接父节点和深度,然后在预处理fa数组时,逐层计算。查询时,处理两个节点到同一深度后,利用二进制跳跃寻找LCA。 最后,生成相关问题需要考虑用户可能的后续疑问,比如如何选择不同算法、优化方法、应用场景等。根据用户提供的示例问题,应该围绕实现细节、复杂度分析、比较其他方法等方面展开。 总结步骤: 1. 介绍LCA问题及常用方法,重点说明倍增法。 2. 提供模板代码,详细注释关键部分,尤其是预处理和查询函数。 3. 解释代码中的关键步骤,如状态转移方程、深度调整、二进制跳跃。 4. 分析时间复杂度和适用情况,引用相关的引用内容辅助说明。 5. 生成相关问题,引导用户深入理解。</think>### LCA(最近公共祖先)算法模板与实现 LCA问题通常通过**倍增法**高效解决,其核心是预处理每个节点的$2^k$级祖先信息,实现$O(\log n)$时间复杂度的查询。以下是基于倍增法的模板代码: ```cpp #include <iostream> #include <vector> #include <cmath> using namespace std; const int MAXN = 1e5 + 5; const int LOG = 20; // 根据最大节点数调整,log2(MAXN) vector<int> tree[MAXN]; // 邻接表存储树 int depth[MAXN]; // 节点深度 int fa[MAXN][LOG]; // fa[i][j]表示节点i的2^j级祖先 // 预处理:DFS初始化depth和直接父节点 void dfs(int u, int parent) { fa[u][0] = parent; // 直接父节点 depth[u] = depth[parent] + 1; for (int v : tree[u]) { if (v != parent) { dfs(v, u); } } } // 预处理fa数组(倍增核心) void preprocess(int root, int n) { depth[root] = 0; dfs(root, 0); // 初始化直接父节点 // 状态转移:fa[x][i] = fa[fa[x][i-1]][i-1] for (int j = 1; j < LOG; j++) { for (int i = 1; i <= n; i++) { fa[i][j] = fa[fa[i][j-1]][j-1]; } } } // LCA查询函数 int lca(int u, int v) { // 确保u是更深的节点 if (depth[u] < depth[v]) swap(u, v); // 将u提升到与v同一深度 for (int k = LOG-1; k >= 0; k--) { if (depth[fa[u][k]] >= depth[v]) { u = fa[u][k]; } } if (u == v) return u; // 刚好是祖先的情况 // 共同向上跳跃寻找LCA for (int k = LOG-1; k >= 0; k--) { if (fa[u][k] != fa[v][k]) { u = fa[u][k]; v = fa[v][k]; } } return fa[u][0]; } ``` #### 关键点说明 1. **预处理复杂度**:DFS遍历$O(n)$,倍增数组构建$O(n \log n)$[^4] 2. **查询复杂度**:每次$O(\log n)$,适合多次查询场景 3. **核心操作**:通过二进制跳跃(如$2^0, 2^1, 2^2...$级祖先)快速调整节点深度 #### 应用场景 - 树结构中的路径查询(如求两点间最短路径长度) - 网络路由算法中的拓扑分析 - 结合树状数组处理动态树问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值