LCA模板(数剖实现)
生活随笔
收集整理的這篇文章主要介紹了
LCA模板(数剖实现)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:https://www.luogu.org/problemnew/show/P3379
題意:LCA模板題。
思路:今天開始學樹剖,先拿lca練練。樹剖解lca,兩次dfs復雜度均為O(n),每次查詢為logn,因此總復雜度為:O(2*n+m*logn)。
代碼:
#include<cstdio> #include<cstring> using namespace std;const int maxn=500005;struct node{int v,next; }edge[2*maxn];int n,m,s,cnt,size[maxn],head[maxn],depth[maxn],son[maxn],fa[maxn],top[maxn];void add(int u,int v){edge[++cnt].v=v;edge[cnt].next=head[u];head[u]=cnt; }void dfs1(int x){size[x]=1;depth[x]=depth[fa[x]]+1;for(int i=head[x];i;i=edge[i].next){int v=edge[i].v;if(v==fa[x]) continue;fa[v]=x;dfs1(v);size[x]+=size[v];if(!son[x]||size[son[x]]<size[v])son[x]=v;} }void dfs2(int x,int f){top[x]=f;if(son[x]) dfs2(son[x],f);for(int i=head[x];i;i=edge[i].next){int v=edge[i].v;if(v==fa[x]||v==son[x]) continue;dfs2(v,v);} }void lca(){for(int i=0;i<m;++i){int x,y;scanf("%d%d",&x,&y);while(top[x]!=top[y]){if(depth[top[x]]>depth[top[y]]) x=fa[top[x]];else y=fa[top[y]];}printf("%d\n",depth[x]<depth[y]?x:y);} }int main(){scanf("%d%d%d",&n,&m,&s);for(int i=1;i<n;++i){int u,v;scanf("%d%d",&u,&v);add(u,v);add(v,u);}dfs1(s);dfs2(s,s);lca();return 0; }?
轉載于:https://www.cnblogs.com/FrankChen831X/p/11167037.html
總結
以上是生活随笔為你收集整理的LCA模板(数剖实现)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大华网络摄像头ip搜索工具_【技术篇】N
- 下一篇: mybatis官网下载