LCA应用——树结构求两点最短距离(倍增法和tarjan)

给出 n 个点的一棵树,多次询问两点之间的最短距离。

注意:

边是无向的。
所有节点的编号是 1,2,…,n 。
输入格式
第一行为两个整数 n 和 m 。 n 表示点数, m 表示询问次数;

下来 n−1 行,每行三个整数 x,y,k ,表示点 x 和点 y 之间存在一条边长度为 k ;

再接下来 m 行,每行两个整数 x,y ,表示询问点 x 到点 y 的最短距离。

树中结点编号从 1 到 n 。

输出格式
共 m 行,对于每次询问,输出一行询问结果。

数据范围
2≤n≤104 ,
1≤m≤2×104 ,
0<k≤100 ,
1≤x,y≤n
输入样例1:
2 2
1 2 100
1 2
2 1
输出样例1:
100
100
输入样例2:
3 2
1 2 10
3 1 15
1 2
3 2
输出样例2:
10
25

如果依旧采用倍增法的代码,在线做法,一个询问给出一个输出。

#include <bits/stdc++.h>

using namespace std;
const int N = 21010;
int n,m;
int deep[N];
int pre[N][22];
int head[N];
int cnt;
struct node
{
    int to,ne,w;
}a[N];
int dis[N];
void add(int x,int y,int z)
{
    cnt++;
    a[cnt].to=y;
    a[cnt].w = z;
    a[cnt].ne = head[x];
    head[x] = cnt;
}
void dfs(int x)
{
    for(int i = head[x];i!=-1;i=a[i].ne)
    {
        int now = a[i].to;
        if(!deep[now])
        {
            deep[now] = deep[x]+1;
            pre[now][0] = x;
            dis[now] = dis[x] +a[i].w;
            dfs(now);
        }
    }
}
int lca(int x,int y)
{
    if(deep[x]>deep[y])
    {
        swap(x,y);
        ans = 2;
    }
    for(int i=20;i>=0;i--)
    if(deep[pre[y][i]]>=deep[x])
    y = pre[y][i];
    if(x==y)
    return x;
    for(int i=20;i>=0;i--)
    if(pre[y][i]!=pre[x][i])
    y = pre[y][i],x=pre[x][i];
   return pre[x][0];
}
int main()
{
    cin >> n>>m;
    memset(head,-1,sizeof(head));
    for(int i=1;i<n;i++)
    {
        int x,y,z;
        cin >> x >>y >>z;
        add(x,y,z);
        add(y,x,z);
    }
    deep[1]=1;
    dfs(1);
    for(int i=1;i<=20;i++)
    for(int j = 1;j<=20010;j++)
    pre[j][i] = pre[pre[j][i-1]][i-1];
    for(int i=1;i<=m;i++)
    {
        int x,y;
        cin >> x>>y;
        if(x==y)
        cout <<"0"<<endl;
        else
        {
            int p = lca(x,y);
            cout <<dis[x]+dis[y]-2*dis[p]<<endl;
        }
    }
    return 0;
}

运用tarjan做法求LCA,离线做法,将所有询问保存下来,最后输出。
对询问元素的配对元素进行检查,若配对元素st[x]==2代表此元素已经回溯,可以用并查集求这个元素的祖先,找到的这个祖先就是双方元素的LCA。

#include <bits/stdc++.h>

using namespace std;
const int N = 20010;
int head[N],dis[N],pre[N],cnt,deep[N],ans[N],st[N];
int n,m;
vector<pair<int,int> > v[N];
struct node
{
    int to,w,ne;
} a[N];
void add(int x,int y,int z)
{
    cnt++;
    a[cnt].to = y;
    a[cnt].w = z;
    a[cnt].ne = head[x];
    head[x] = cnt;
}
int  ffind(int x)
{
    if(x==pre[x])
        return x;
    return pre[x]=ffind(pre[x]);
}
void dfs(int x)
{
    for(int i=head[x]; i!=-1; i=a[i].ne)
    {
        int now = a[i].to;
        if(!deep[now])
        {
            deep[now] = deep[x]+1;
            dis[now] = dis[x]+a[i].w;
            dfs(now);
        }
    }
}
void tarjan(int x)
{
    st[x] = 1;
    for(int i=head[x]; i!=-1; i=a[i].ne)
    {
        int now = a[i].to;
        if(!st[now])
        {
            tarjan(now);
            pre[now] = x;
        }
    }
    for(auto each:v[x])
    {
        int xx = each.first,yy = each.second;
        if(st[xx] == 2)
        {
            int k = ffind(xx);
            ans[yy] = dis[x]+dis[xx]-2*dis[k];
        }
    }

    st[x] = 2;
}
int main()
{
    memset(head,-1,sizeof(head));
    cin >> n >>m;
    for(int i=1; i<n; i++)
    {
        int x,y,z;
        cin >> x >>y >>z;
        add(x,y,z);
        add(y,x,z);
    }
    deep[1] = 1;
    for(int i=1; i<=n; i++)
        pre[i] = i;
    dfs(1);
    for(int i=1; i<=m; i++)
    {
        int x,y;
        cin >> x >>y;
        v[x].push_back({y,i});
        v[y].push_back({x,i});
    }
    tarjan(1);
    for(int i=1; i<=m; i++)
    {
        cout <<ans[i]<<endl;
    }
    return 0;
}

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
预处理 第一遍dfs每个结点的深度deep[x],其为根的子大小size[x] 以及祖先的信息fa[x][i]表示x往上距离为2^i的祖先 第二遍dfs ž根节点为起点,向下拓展构建重链 选择最大的一个子的根继承当前重链 其余节点,都以该节点为起点向下重新拉一条重链 ž给每个结点分配一个位置编号,每条重链就相当于一段区间,用数据结构去维护。 把所有的重链首尾相接,放到同一个数据结构上,然后维护这一个整体即可 修改操作 ž1、单独修改一个点的权值 根据其编号直接在数据结构中修改就行了。 2、修改点u和点v的路径上的权值 (1)若u和v在同一条重链上 直接用数据结构修改pos[u]至pos[v]间的值。 (2)若u和v不在同一条重链上 一边进行修改,一边将u和v往同一条重链上靠,然后就变成了情况(1)。 伪代码 CHANGE (x, y ,d) while top[x]≠top[y] do if dep[top[x]]<dep[top[y]] then SWAP(x,y), SWAP (gx,gy) CHANGE-IT(tid[top[x]],tid[x],d) fa[x]→x if dep[x]>dep[y] then SWAP (x,y) CHANGE-IT(tid[x],tid[y],d) //CHANGE-IT(l,r,d)为数据结构的修改操作:将区间[l,r]上的所有权值改为d 查询操作 ž查询操作的分析过程同修改操作 伪代码 QUERY (x, y) while top[x]≠top[y] do if dep[top[x]]<dep[top[y]] then SWAP (x,y), SWAP (gx,gy) QUERY-IT(tid[top[x]],tid[x]) fa[x]→x if dep[x]>dep[y] then SWAP (x,y) QUERY-IT(tid[x],tid[y]) //QUERY-IT(l,r)为数据结构的查询操作, 题目不同,选用不同的数据结构来维护值,通常有线段和splay [2]
以下是使用C++编写的二叉两点短距离的代码示例: ```cpp #include <iostream> #include <queue> struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} }; // 寻找最低公共祖先节点 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (root == nullptr || root == p || root == q) { return root; } TreeNode* left = lowestCommonAncestor(root->left, p, q); TreeNode* right = lowestCommonAncestor(root->right, p, q); if (left && right) { return root; } else if (left) { return left; } else { return right; } } // 计算节点到最低公共祖先节点的距离 int distanceToLCA(TreeNode* node, TreeNode* target) { if (node == nullptr) { return INT_MAX; } if (node == target) { return 0; } return 1 + std::min(distanceToLCA(node->left, target), distanceToLCA(node->right, target)); } // 计算最短距离 int shortestDistance(TreeNode* root, TreeNode* p, TreeNode* q) { TreeNode* lca = lowestCommonAncestor(root, p, q); int distance_p = distanceToLCA(lca, p); int distance_q = distanceToLCA(lca, q); return distance_p + distance_q; } int main() { // 创建二叉 TreeNode* root = new TreeNode(3); root->left = new TreeNode(5); root->right = new TreeNode(1); root->left->left = new TreeNode(6); root->left->right = new TreeNode(2); root->right->left = new TreeNode(0); root->right->right = new TreeNode(8); root->left->right->left = new TreeNode(7); root->left->right->right = new TreeNode(4); // 寻找节点5和节点4的最短距离 int distance = shortestDistance(root, root->left, root->left->right->right); std::cout << distance << std::endl; // 输出2,即节点5和节点4之间的最短距离 return 0; } ``` 请注意,此示例代码中使用了C++标准库的queue和iostream头文件,并假设了中的节点值不重复。在实际应用中,你可能需要根据具体情况进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值