【模板】lca 最近公共祖先
2017-11-04 10:29
435 查看
lca:
hljs cpp">#include<cstring> #include<algorithm> using namespace std; const int MAXN=500001; int n,m,gen,x,y; struct Edge{ int next,to; }edge[2*MAXN]; int deep[MAXN],fa[MAXN][20];//deep记录每个点的深度,fa[i][j]:表示节点向上跳2^j 个节点所能到达的节点 //显然fa[i][0]就是直接的父节点了 int num_edge,head[MAXN]; void add_edge(int from,int to) { edge[++num_edge].next=head[from]; edge[num_edge].to=to; head[from]=num_edge; } bool vis[MAXN]; void dfs(int x)//保存f[i][0] { vis[x]=true; for (int i=1; i<=16; i++) { if ((1<<i)>deep[x]) break; fa[x][i]=fa[fa[x][i-1]][i-1]; } for (int i=head[x]; i!=0; i=edge[i].next) { if (!vis[edge[i].to]) { deep[edge[i].to]=deep[x]+1; fa[edge[i].to][0]=x; dfs(edge[i].to); } } } int lca(int x,int y) { if (deep[x]<deep[y]) swap(x,y); int d=deep[x]-deep[y]; for (int i=0; i<=16; i++) { if ((1<<i)&d) x=fa[x][i];//判断d的第i位是否为1,是的话就往上跳 } if (x==y) return x; for (int i=16; i>=0; i--)//因为要找最深的公共祖先,所以要倒着循环 { if (fa[x][i]!=fa[y][i]) { x=fa[x][i];//一起往上跳到最近公共祖先的下面 y=fa[y][i]; } } return fa[x][0]; } int main() { scanf("%d%d%d",&n,&m,&gen); for (int i=1; i<=n-1; i++) { scanf("%d%d",&x,&y); add_edge(x,y); add_edge(y,x); } dfs(gen); for (int i=1; i<=m; i++) { scanf("%d%d",&x,&y); printf("%d\n",lca(x,y)); } return 0; } /* 5 5 4 3 1 2 4 5 1 1 4 2 4 3 2 3 5 1 2 4 5 4 4 1 4 4 */
相关文章推荐
- 洛谷3379 【模板】最近公共祖先(LCA)
- 洛谷 P3379 【模板】最近公共祖先(LCA)
- [Luogu P3379]【模板】最近公共祖先(LCA)
- P3379 【模板】最近公共祖先(LCA)
- HDU 2586 How far away ?(LCA模板 最近公共祖先啊)
- AC日记——【模板】最近公共祖先(LCA)洛谷 P3379
- LCA 最近公共祖先 (笔记、模板)
- 4000 【模板】最近公共祖先(LCA)
- 树剖——【模板】最近公共祖先(LCA)
- lca最近公共祖先(模板)
- hihoCoder_#1067_最近公共祖先·二(LCA+tarjan模板)
- tarjan离线算法-LCA最近公共祖先算法模板(详细)
- 【洛谷】3379 【模板】最近公共祖先(LCA)
- 【模板】最近公共祖先(LCA)
- 倍增法求最近公共祖先(LCA)的算法模板
- 连通分量模板:tarjan: 求割点 && 桥 && 缩点 && 强连通分量 && 双连通分量 && LCA(最近公共祖先)
- [模板]最近公共祖先LCA
- 【LCA倍增模板】【poj1330】最近公共祖先
- 【模板】最近公共祖先(LCA)
- 洛谷——P3379 【模板】最近公共祖先(LCA)