P3379 【模板】最近公共祖先(LCA)题解

· · 题解

这是蒟蒻的第一篇题解 大佬勿喷

做法:时间戳+二分 复杂度O(N\log^2 N)

题目描述:

给定一棵有根多叉树,请求出指定两个点之间最近的公共祖先。

思路:

暴力跳已于 2021/10/4 卡掉

暴力:

简单优化一下的暴力最坏复杂度为O(N*M) 当然过不了

蒟蒻的暴力思路:hash+q向上寻找祖先

第一个它的祖先也是p的祖先为最近公共祖先

hash[i][j]==true 表示 i是j的最近公共祖先

代码很明显 但空间为O(N^2) 时间O(N*M)

优化空间:

此时会想到**时间戳区间**或 **括号序(Parenthesis Ordering)** 优化空间 及**dfs序+子树遍历结束值** dfs序是**先序遍历序**(如果不会先序遍历 或 dfs请先学习 在此蒟蒻不在过多赘述) 用两个数组 **hin[N]** 和 **hou[N]** 存储dfs序和子树遍历结束值 #### 如何比较hin和hou来得到是否为祖先呢? >如果遍历比他晚的(及dfs序比其大的) 肯定不是他的祖先 > >**因为先序便利为先根后子树 那么祖先肯定在其上方** > >如果结束比他早的话 肯定不是他的祖先 > >**因为遍历完子树再记录子树遍历结束值,祖先结束值肯定比其晚** #### 为什么要dfs序+子树遍历结束值? 不直接dfs序或子树遍历结束值呢 > >举个例子 > >根节点是 1 左孩子是2 右孩子是3 >##### 如果只有dfs序 发生问题: >dfs序hin[1]=1 hin[2]=2 hin[3]=3 > >2是3的祖先么 > >hin[2]<=hin[3] 是 但**实际上2不是3的祖先** > >##### 如果只有结束值 发生问题: > >结束值hou[1]=3 hou[2]=2 hou[3]=3 > >3是2的祖先么 > >hou[3]>=hou[2] 但**实际上3不是2的祖先** > >而如果dfs序+子树遍历结束值 **祖先的子树范围便有了起点,终点** 可以判断祖先了 代码如下: ```cpp int times=0;//全局变量 inline void dfs(int u,int fa){ hin[u]=times++; for(auto v:e[u]){ if(v==fa) continue; dfs(v,u); } hou[u]=times; } ``` --- ### 优化时间: $O(N*M)$ 必炸 过不了 想办法得优化到M log^2 N级别或M log N级别甚至线性 因为深度**从下往上依次递减** 最近公共祖先是深度最少 很容易想到**二分** ~~二分虽简单 但应用场景很广 学好二分很重要~~ 很明显是**深度二分** 但二分的是深度 但这一层有很多 所以我们要找这一层**p的祖先** ~~q的祖先也行~~ 但一次次找这一层p的祖先很麻烦且复杂度又上来了 想到 定义up[i][p]**表示p向上走i步**(及深度)的下标 但**预处理复杂度**依旧很高 可以用**二进制拆分** #### 为什么要用二进制呢 因为**二进制快**(位运算 逻辑运算复杂度 都为1) 在dfs中添加 ```cpp up[0][u]=fa; for(int i=1;i<?;i++) up[i][u]=up[i-1][up[i-1][u]]; ``` 这里?为最多需 **二进制位数** 定义logg 你既可以直接定义为20 也可定义为$\log_2\N

两种都行

up[i][u]=up[i-1][up[i-1][u]]; 表示 到达2^i步需要先走2^{i-1}到mid 再走2^{i-1}步

但注意 需要定义 up[0][u]=fa; 因为如果直接用公式 数组越界

因为二分的是深度 所以需要用到dep

伪代码

dep[u]=dep[祖先]+1

直接在dfs地方遍历加上

因为用到二进制拆分

所以定义一个函数

lift(q,i) 表示q向上走i步到达的点

代码:

inline int lift(int q,int st){
for(int i=0;i<logg;i++)
if((st&(1<<i))!=0) q=up[i][q];
return q;
}

这是从2^0到2^{logg}

1<<i 表示 2^i(如果没学好位运算请学习)

如果(st&(1<<i))==0 表示st二进制中第i位为0

二分部分

inline int lca(int p,int q){
if(dep[p]<dep[q]) swap(p,q);
int low=0,he=dep[p];
int ans=0;
while(low<=he){
int mid=(low+he)/2;
int step=dep[p]-mid;
int u=lift(p,step);
if(hin[u]<=hin[q] && hou[u]>=hou[q]){
ans=u;
low=mid+1;
}
else he=mid-1;
}
return ans;
}

未优化常数的代码:

#include<bits/stdc++.h>
using namespace std;
const int N=5e5+66;
int n,m,s;
vector<int>e[N];
int logg=0;
inline int read(){
int ch=0;
int ans=0;
ch=getchar();
while(ch<'0' || ch>'9'){
ch=getchar();
}
while(ch>='0' && ch<='9'){
ans*=10;
ans+=ch-'0';
ch=getchar();
}
return ans;
}
int dep[N],hin[N],hou[N],times,up[30][N];
inline void dfs(int u,int fa){
hin[u]=times++;
up[0][u]=fa;
for(int i=1;i<logg;i++) up[i][u]=up[i-1][up[i-1][u]];;
for(auto v:e[u]){
if(v==fa) continue;
dep[v]=dep[u]+1;
dfs(v,u);
}
hou[u]=times;
}
inline int lift(int q,int st){
for(int i=0;i<logg;i++)
if((st&(1<<i))!=0) q=up[i][q];
return q;
}
inline int lca(int p,int q){
if(dep[p]<dep[q]) swap(p,q);
int low=0,he=dep[p];
int ans=0;
while(low<=he){
int mid=(low+he)/2;
int step=dep[p]-mid;
int u=lift(p,step);
if(hin[u]<=hin[q] && hou[u]>=hou[q]){
ans=u;
low=mid+1;
}
else he=mid-1;
}
return ans;
}
int main(){
     n=read();
    m=read();
    s=read();
    for(int i=1;i<n;i++){
    int x,y;
    x=read();
    y=read();
    e[x].push_back(y);
    e[y].push_back(x);
    }
    while((1<<logg)<=n) logg++;
    dfs(s,0);
    for(int i=1;i<=m;i++){
     int a,b;
    a=read();
    b=read();
    printf("%d\n",lca(a,b));
    }
    return 0;
}

但是会别第二组数据给卡掉\ 记录

优化常数

代码:

#include<bits/stdc++.h>
using namespace std;
const int N=5e5+66;
int n,m,s;
vector<int>e[N];
int logg=0;
const int OUT= 1<<20;
char outb[OUT];
int outt=0;
inline void flush() {
    if (outt){
    fwrite(outb,1,outt, stdout);
    outt=0;
    }
}
inline void write(int x) {
    if (x>=10) write(x/10);
    outb[outt++] = '0'+x%10;
    if (outt>= OUT-10) flush(); 
}
inline int read(){
int ch=0;
int ans=0;
ch=getchar();
while(ch<'0' || ch>'9'){
ch=getchar();
if(ch==EOF) return 0;
}
while(ch>='0' && ch<='9'){
ans*=10;
ans+=ch-'0';
ch=getchar();
}
return ans;
}
int dep[N],hin[N],hou[N],times,up[30][N];
inline void dfs(int u,int fa){
hin[u]=times++;
up[0][u]=fa;
for(int i=1;i<logg;i++) up[i][u]=up[i-1][up[i-1][u]];;
for(auto v:e[u]){
if(v==fa) continue;
dep[v]=dep[u]+1;
dfs(v,u);
}
hou[u]=times;
}
inline int lift(int q,int st){
for (int i=0;st;++i,st>>=1) {
if (st&1) q = up[i][q];
}
return q;
}
inline int lca(int p,int q){
if(dep[p]<dep[q]) swap(p,q);
p = lift(p,dep[p]-dep[q]);      
if (p==q) return p;
int low=0,he=dep[q]-1;
int ans=0,m=dep[p],sh=p;
while(low<=he){
int mid=(low+he)/2;
int step,u;
    if(mid<m){
    step=m-mid;
    u=lift(sh,step);
    }
else{
step=dep[p]-mid;
u=lift(p,step);
}
if(hin[u]<=hin[q] && hou[u]>=hou[q]){
ans=u;
low=mid+1;
}
else he=mid-1;
m=mid;
sh=u;
}
return ans;
}
int main(){
     n=read();
    m=read();
    s=read();
    for(int i=1;i<n;i++){
    int x,y;
    x=read();
    y=read();
    e[x].push_back(y);
    e[y].push_back(x);
    }
    while((1<<logg)<=n) logg++;
    dfs(s,0);
    for(int i=1;i<=m;i++){
     int a,b;
    a=read();
    b=read();
    write(lca(a,b));
    outb[outt++] = '\n';
    if (outt>= OUT-10) flush();
    }
    flush();
    return 0;
}

成功AC

但如果你还能优化的话会发现有时候时间限制1s也没事 代码

#include <bits/stdc++.h>
using namespace std;
const int N=5e5+66;
int n,m,s;
vector<int>e[N];
int logg=0;
const int OUT= 1<<20;
char outb[OUT];
int outt=0;
inline void flush() {
    if (outt){
    fwrite(outb,1,outt, stdout);
    outt=0;
    }
}
inline void write(int x) {
    if (x>=10) write(x/10);
    outb[outt++] = '0'+x%10;
    if (outt>= OUT-10) flush(); 
 }
 inline int read(){
 int ch=0;
 int ans=0;
 ch=getchar();
 while(ch<'0' || ch>'9'){
 ch=getchar_unlocked();
 if(ch==EOF) return 0;
 }
 while(ch>='0' && ch<='9'){
 ans*=10;
 ans+=ch-'0';
 ch=getchar_unlocked();
 }
return ans;
}
int dep[N],hin[N],hou[N],times,up[30][N];
//struct node{int da,fu;};
//bool operator <(const node &a,const node &b){return a.da<b.da;}
inline void dfs(int u,int fa){
/*int farth[N];
vector<int>leaf;
priority_queue<node>q;
stack<node>st;
st.push(node{u,fa});
while(!st.empty()){
int u=st.top().da,fa=st.top().fu;
farth[u]=fa;
st.pop();
hin[u]=times++;
up[0][u]=fa;
for(int i=1;i<logg;i++) up[i][u]=up[i-1][up[i-1][u]];;
for(auto v:e[u]){
if(v==fa) continue;
dep[v]=dep[u]+1;
st.push(node{v,u});
}
if(e[u].size()==1 && u!=s) leaf.push_back(u); // 只有一个与父亲节点相连
}
for(auto v:leaf){hou[v]=hin[v]; q.push(node{hou[v],v});}
while(!q.empty()){
int f=q.top().fu;
q.pop();
int fa=farth[f];
if(hou[f]>hou[fa]){
q.push(node{hou[fa],fa});
hou[fa]=hou[f];
}
}*/
static int st[N], it[N];   
    int top=0;
    st[++top]=s;
    hin[s]=++times;
    dep[s]=0;
    up[0][s]=0;
    it[s]=0;

    while (top) {
        int u=st[top];
        if (it[u]<(int)e[u].size()) {
            int v=e[u][it[u]++];
            if (v==up[0][u]) continue;   
            up[0][v]=u;
            dep[v]=dep[u] + 1;
            hin[v]=++times;
            st[++top]=v;
            it[v]=0;
        } else {
            hou[u]=times;  
            top--;
        }
    }
}
inline int lift(int q,int st){
for (int i=0;st;++i,st>>=1) {
if(st&1) q = up[i][q];
}
return q;
}
inline int lca(int p,int q){
if(hin[p]<=hin[q] && hou[p]>=hou[q]){
return p;
}
if(hin[p]>=hin[q] && hou[p]<=hou[q]){
return q;
}
if(dep[p]<dep[q]) swap(p,q);
p = lift(p,dep[p]-dep[q]);      
if (p==q) return p;
int low=0,he=dep[q]-1;
int ans=0;
while(low<=he){
int mid=(low+he)/2;
int step,u;
step=dep[p]-mid;
u=lift(p,step);
if(hin[u]<=hin[q] && hou[u]>=hou[q]){
ans=u;
low=mid+1;
}
else{he=mid-1; p=u;}
}
return ans;
}
int main(){
     n=read();
    m=read();
    s=read();
    for(int i=1;i<n;i++){
    int x,y;
    x=read();
    y=read();
    e[x].push_back(y);
    e[y].push_back(x);
    }
    while((1<<logg)<=n) logg++;
    dfs(s,0);
    for (int i=1;i<logg;i++)
    for (int j=1; j<=n;j++)
        up[i][j] = up[i-1][up[i-1][j]];
    for(int i=1;i<=m;i++){
     int a,b;
    a=read();
    b=read();
    write(lca(a,b));
    outb[outt++] = '\n';
    if (outt>= OUT-10) flush();
    }
    flush();
    return 0;
}

这个代码优化了输入 并将dfs改为非递归

成功切了这道模板题

注意:此为非正解的做法,正式竞赛尽量用正解\ 总之 要相信常数的威力\ WAW 撒花