【图论】倍增与lca

复制代码
void dfs(long u,long father){
dep[u]=dep[father]+1;//只在这里初始化dep
 
for(long i=1;(1<<i)<=dep[u];i++)
    fa[u][i]=fa[fa[u][i-1]][i-1];//只这里用的倍增
 
for(long i=head[u];~i;i=edge[i].next){
    long v=edge[i].to;
    if(v==father)continue;
    fa[v][0]=u;
    dfs(v,u);
}
 
}
long lca(long x,long y){
if(dep[x]<dep[y])swap(x,y);
 
for(int i=20;i>=0;i--){//跳到同一个深度
    if(dep[fa[x][i]]>=dep[y])x=fa[x][i];
    if(x==y)return x;
}
 
for(int i=20;i>=0;i--){
    if(fa[x][i]!=fa[y][i]){//一起跳
        x=fa[x][i];
        y=fa[y][i];
    }
}
return fa[x][0];
}

提单1
题单2

Head out to the Target

相关推荐
yyy(十一月限定版)32 分钟前
寒假集训4——二分排序
算法
星火开发设计32 分钟前
类型别名 typedef:让复杂类型更简洁
开发语言·c++·学习·算法·函数·知识
醉颜凉43 分钟前
【LeetCode】打家劫舍III
c语言·算法·leetcode·树 深度优先搜索·动态规划 二叉树
达文汐1 小时前
【困难】力扣算法题解析LeetCode332:重新安排行程
java·数据结构·经验分享·算法·leetcode·力扣
一匹电信狗1 小时前
【LeetCode_21】合并两个有序链表
c语言·开发语言·数据结构·c++·算法·leetcode·stl
User_芊芊君子1 小时前
【LeetCode经典题解】搞定二叉树最近公共祖先:递归法+栈存路径法,附代码实现
算法·leetcode·职场和发展
算法_小学生1 小时前
LeetCode 热题 100(分享最简单易懂的Python代码!)
python·算法·leetcode
执着2591 小时前
力扣hot100 - 234、回文链表
算法·leetcode·链表
Gorgous—l1 小时前
数据结构算法学习:LeetCode热题100-多维动态规划篇(不同路径、最小路径和、最长回文子串、最长公共子序列、编辑距离)
数据结构·学习·算法
熬夜造bug1 小时前
LeetCode Hot100 刷题路线(Python版)
算法·leetcode·职场和发展