LCA

void add(int u,int v){
    e[idx] = v;ne[idx] = head[u];head[u] = idx++;
}

void dfs(int u,int father){
    depth[u] = depth[father]+1;
    for(int i=0;i<=19;i++){
        f[u][i+1] = f[u][f[u][i]];
    }
    for(int i = head[u];i;i = ne[i]){
        int v = e[i];
        if( v == father) continue;
        f[v][0] = u;
        dfs(v,u);
    }
}

int LCA(int x,int y){
    if(depth[x] < depth[y]) swap(x,y);
    for(int i=20;i>=0;i--){
        if(depth[f[x][i]]>depth[y]) x = f[x][i];
        if(x==y) return x;
    }
    for(int i =20;i>=0;i--){
        if(f[x][i]!=f[y][i]){
            x = f[x][i];
            y = f[y][i];
        }
    }
    return f[x][0];  //x.y是深度不同且最浅的子节点
}


全部评论

相关推荐

头像
04-17 09:29
已编辑
湖南农业大学 后端
睡姿决定发型丫:本硕末9也是0offer,简历挂了挺多,只有淘天 美团 中兴给了面试机会,淘天二面挂,美团一面kpi面,中兴一面感觉也大概率kpi(虽然国企,但一面0技术纯聊天有点离谱吧)
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
05-01 13:13
ecece:这么明目张胆虚报就业率啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务