首页 > 其他分享 >最近公共祖先 (Lowest Common Ancestor)LCA

最近公共祖先 (Lowest Common Ancestor)LCA

时间:2024-03-29 17:35:58浏览次数:16  
标签:Lowest int deep next fa 祖先 Common LCA

最近公共祖先

img
img
img
img
img
img
img
原文链接

c++代码
#include<bits/stdc++.h>
using namespace std;

constexpr int N =5E5 + 10;

struct edge{
    int to, next; //两个整型成员变量 to 和 next。这个结构体表示了图中的一条边,其中 to 表示边的终点,
                  //next 表示下一条以同一个起点为起始点的边的索引。
}edge[N << 1];

int head[N << 1], cnt;//head[]一直在更新(u,v)中在edge[]的下标位置,cnt表示第几条边
                    //注意由于是无向图所以(u,v)需要存储两条边
void addEdge(int u, int v){
    edge[++cnt].to = v;
    edge[cnt].next = head[u];
    head[u] = cnt;
}

int deep[N], fa[N][20];//deep[x]表示x的深度,fa[x][],father是x的父节点
void dfs(int x, int father){
    deep[x] = deep[father] + 1;//深度比父节点加一
    fa[x][0] = father;//记录x的父节点
    for(int i = 1; (1 << i) < deep[x] ; i++){//1向左移i就相当于1*2^i=2^i,就是在判断当前深度能不能跳2^i步
        fa[x][i] = fa[fa[x][i-1]][i-1];      //记录父节点
    }
    for(int i = head[x]; i; i = edge[i].next){//遍历x的所有孩子节点
        if(edge[i].to != father){
            dfs(edge[i].to, x);
        }
    }
}

int LCA(int u, int v){
    if(deep[u] < deep[v]){
        swap(u, v);//让u是深度较大的点
    }
    //先让u跳到和v相同的高度,然后一起往上跳
    for(int i = 19; i >= 0; --i){//2^19 > 5e5 +10
    //一开始 2^i过于大不会进入if判断
        if(deep[u] - deep[v] >= (1 << i)){//防止u跳过头换一个较小的i
            u = fa[u][i]; //更新 u
        } 
    }
    if(u == v){ //v就是u的祖先
        return u;
    }
    //u,v同时往上跳找到LCA
    for(int i = 19; i >= 0; --i){
        if(fa[u][i] != fa[v][i]){//找到共同祖先之后就不会进入if
            u = fa[u][i];
            v = fa[v][i];
        }
    }
    return fa[u][0];
    // 最后 x 位于 LCA 的下一层, 父节点 fa[x][0] 就是 LCA
}
int main(){
    //N族谱人数,Q工作人员挑选对数

    int n, q, s = 1;
    cin >> n >> q;
    for (int i = 1; i <= n - 1; i++) {
        int x, y;
        cin >> x >> y;
        addEdge(x, y); addEdge(y, x);//无向图
    }
    dfs(s, 0);//从根节点开始搜
    for (int i = 1; i <= q; i++) {
        int x, y;
        cin >> x >> y;
        cout << LCA(x, y) << endl;
    }
    return 0;
}

输入:
3 1
1 2
1 3
2 3
输出:
1

标签:Lowest,int,deep,next,fa,祖先,Common,LCA
From: https://www.cnblogs.com/kz7430/p/18092183

相关文章

  • teamcenter中 import com.teamcenter.rac.commonclient.date.DateComponent;的使用
     渲染:Datedate=null; TCPropertyDescriptordescriptor=property.getDescriptor(); Stringpropertyname=descriptor.getName(); if("EOL_Date".equals(propertyname)){// DateComponenta=newDateComponent(); date=property.getDateVa......
  • 最近公共祖先(lca)倍增算法【模板】
    P3379【模板】最近公共祖先(LCA)-洛谷|计算机科学教育新生态(luogu.com.cn)#include<bits/stdc++.h>#include<cstdio>usingnamespacestd;constintN=5e5+100;constintinf=0x3f3f3f;intn,m,s;vector<int>g[N];intdep[N];//存u点的深度intfa[N][20];//存从u......
  • Authentication failed. Some common reasons include:
    问题无论是pull、clone还是push都报错fatal:Outofmemory,mallocfailed(triedtoallocate301989888bytes)fatal:Couldnotreadfromremoterepository.Pleasemakesureyouhavethecorrectaccessrightsandtherepositoryexists.解决方法gitconfig--globalh......
  • CF1271E - Common Number |
    links设\(f(x)=\begin{cases}x-1,&x\mod2=1\\\dfrac{x}{2},&x\mod2=0\\\end{cases}\)若将一个数\(x\)不断赋值为\(f(x)\)直到\(x=1\),则在这个过程中出现的数的集合我们称之为\(path(x)\),如\(path(7)=\{7,6,3,2,1\}\),\(path(4)=......
  • Postgresql Common Commands
    PSQL快捷命令cat~/.psqlrc--checkactivesession\setactive_session'selectpid,usename,datname,application_name,client_addr,age(clock_timestamp(),query_start),queryfrompg_stat_activitywherepid<>pg_backend_pid()andstate=\'active\......
  • const [increaseBigCats, increaseSmallCats] = useCatStore( (state) => [state.incr
    const[increaseBigCats,increaseSmallCats]=useCatStore((state)=>[state.increaseBigCats,state.increaseSmallCats],shallow);这段代码是在使用zustand这个React状态管理库。zustand提供了一种简洁的方式来创建可复用的状态存储,并允许组件通过hoo......
  • foxy rviz2 "rviz_common/Time"报错问题
    报错内容Theclassrequiredforthispanel,'rviz_common/Time',couldnotbeloaded.Error:Accordingtotheloadedplugindescriptionstheclassrviz_common/Timewithbaseclasstyperviz_common::Paneldoesnotexist.DeclaredtypesareTeleopPanel......
  • 如何在Kubernetes集群中集成Cromwell和Volcano(概述)
    将Cromwell和Volcano在Kubernetes集群中集成,使用Volcano作为Cromwell调度器,涉及到在Kubernetes集群上安装和配置这两个系统以及确保它们能够无缝协作。以下是一个基于理解和实际操作经验的概括步骤,旨在指导如何进行这一集成:步骤1:安装Kubernetes集群确保你已经......
  • 51nod2599 最近公共祖先LCA
    给定一颗n个节点的树,根节点编号为1,有Q组询问,每次给定一对节点编号(x,y),求(x,y)的最近公共祖先。求LCA有多种方法,这里给的是倍增法,预处理时间O(nlogn),单次查询时间O(logn),支持在线。#include<bits/stdc++.h>usingnamespacestd;#defineintlonglong#definerep(i,a,b)for......
  • AcWing 1171. 距离 Tarjan算法离线求LCA
    题目输入样例1:22121001221输出样例1: 100100输入样例2:32121031151232输出样例2: 1025LCA算法:LCA(LeastCommonAncestors)最近公共祖先Tarjan求LCA是一种离线的算法,也就是说它一遍求出所有需要求的点的LCA,而不是需要求哪两个点再去求......