版本比较
浅谈LCA
正文
增加 9 行删除 9 行
15 行未改动161718192021222324252627282930313295 行未改动1281291301311321331341351364 行未改动14114214314414514614714814923 行未改动173174175176177178179180181123 行未改动全部展开30530630730830931031131231333 行未改动34734834935035135235335435510 行未改动36636736836937037137237337441 行未改动41641741841942042142242342449 行未改动15 行未改动------------## Ⅰ 暴力搜索最容易想到的,也最容易实现的,是对于每个节点,用 $O(n)$的时间维护一个深度数组 $depth[]$ ,然后从每个询问的点遍历其祖先,两个询问点的公共祖先中 $depth[]$ 最小的即为答案。每次查询的平均时间复杂度为$O(logn)$,即该树的深度,最坏时间复杂度为$O(n)$,对于本题可能会$TLE$。------------## Ⅱ 优化算法#### 既然暴力会$TLE$,那么就让我们考虑一下优化算法。------------95 行未改动elsest[i][j]=b;}}}inline int lca(int x,int y){//询问x=fst[x];y=fst[y];if(x>y)4 行未改动if(depth[a]<depth[b])//查询区间最小值return dfn[a];elsereturn dfn[b];}```#### 完整代码请见文末23 行未改动if(vis[query[qid].y])query[qid].lca=find(query[qid].y);elseif(vis[query[qid].x])query[qid].lca=find(query[qid].x);}for(auto v:g[u]){if(vis[v])continue;123 行未改动全部展开while('0'<=ch&&ch<='9')x=x*10+ch-'0',ch=getchar();return x*f;}int cnt=0;inline void dfs(int cur,int dep){fst[cur]=++cnt;dfn[cnt]=cur;33 行未改动if(depth[a]<depth[b])return dfn[a];elsereturn dfn[b];}int main(){lg[0]=-1;for(int i=1;i<maxn*2;i++)lg[i]=lg[i>>1]+1;10 行未改动dfs(s,0);ST_init();while(m--){x=read();y=read();cout<<lca(x,y)<<endl;}return 0;}/*41 行未改动if(vis[query[qid].y])query[qid].lca=find(query[qid].y);}else if(vis[query[qid].x])query[qid].lca=find(query[qid].x);}for(auto v:g[u]){if(vis[v])continue;49 行未改动15 行未改动161718192021222324252627282930313295 行未改动1281291301311321331341351364 行未改动14114214314414514614714814923 行未改动173174175176177178179180181123 行未改动全部展开30530630730830931031131231333 行未改动34734834935035135235335435510 行未改动36636736836937037137237337441 行未改动41641741841942042142242342449 行未改动15 行未改动------------## Ⅰ 暴力搜索最容易想到的,也最容易实现的,是对于每个节点,用 $O(n)$的时间维护一个深度数组 $depth[]$ ,然后从每个询问的点遍历其祖先,两个询问点的公共祖先中 $depth[]$ 最小的即为答案。每次查询的平均时间复杂度为$O(logn)$,即该树的深度,最坏时间复杂度为$O(n)$,对于本题可能会$TLE$。------------## Ⅱ 优化算法#### 既然暴力会$TLE$,那么就让我们考虑一下优化算法。------------95 行未改动elsest[i][j]=b;}}}inline int lca(int x,int y){//询问x=fst[x];y=fst[y];if(x>y)4 行未改动if(depth[a]<depth[b])//查询区间最小值return dfn[a];elsereturn dfn[b];}```#### 完整代码请见文末23 行未改动if(vis[query[qid].y])query[qid].lca=find(query[qid].y);elseif(vis[query[qid].x])query[qid].lca=find(query[qid].x);}for(auto v:g[u]){if(vis[v])continue;123 行未改动全部展开while('0'<=ch&&ch<='9')x=x*10+ch-'0',ch=getchar();return x*f;}int cnt=0;inline void dfs(int cur,int dep){fst[cur]=++cnt;dfn[cnt]=cur;33 行未改动if(depth[a]<depth[b])return dfn[a];elsereturn dfn[b];}int main(){lg[0]=-1;for(int i=1;i<maxn*2;i++)lg[i]=lg[i>>1]+1;10 行未改动dfs(s,0);ST_init();while(m--){x=read();y=read();cout<<lca(x,y)<<endl;}return 0;}/*41 行未改动if(vis[query[qid].y])query[qid].lca=find(query[qid].y);}else if(vis[query[qid].x])query[qid].lca=find(query[qid].x);}for(auto v:g[u]){if(vis[v])continue;49 行未改动