日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【模板】LCA

發(fā)布時間:2023/12/20 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【模板】LCA 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

最近公共祖先LCA

1 #include<bits/stdc++.h> 2 #define MAX 10000001 3 4 using namespace std; 5 namespace edge_and_question{ 6 int tot,q_tot; 7 int head[MAX],q_head[MAX]; 8 9 struct data{ 10 int to; 11 int nxt; 12 int lca; 13 }edge[MAX],q_edge[MAX]; 14 15 void link_p(int u,int v){ 16 edge[++tot].to=v; 17 edge[tot].nxt=head[u]; 18 head[u]=tot; 19 } 20 21 void link_q(int u,int v){ 22 q_edge[++q_tot].to=v; 23 q_edge[q_tot].nxt=q_head[u]; 24 q_head[u]=q_tot; 25 } 26 } 27 using namespace edge_and_question; 28 namespace LCA{ 29 int fa[MAX],visit[MAX]; 30 inline int father(int x){ 31 return fa[x]==x?x:father(fa[x]); 32 } 33 inline int dfs(int u){ 34 fa[u]=u; 35 visit[u]=1; 36 for(register int k=head[u];k;k=edge[k].nxt){ 37 int v=edge[k].to; 38 if(!visit[v]){ 39 dfs(v); 40 fa[v]=u; 41 } 42 } 43 for(register int k=q_head[u];k;k=q_edge[k].nxt){ 44 int v=q_edge[k].to; 45 if(visit[v]){ 46 q_edge[k].lca=father(v); 47 if(k%2) 48 q_edge[k+1].lca=q_edge[k].lca; 49 else 50 q_edge[k-1].lca=q_edge[k].lca; 51 } 52 } 53 } 54 } 55 using namespace LCA; 56 namespace main_project{ 57 int n,m,root; 58 int u,v; 59 60 void scan(){ 61 scanf("%d%d%d",&n,&m,&root); 62 for(register int i=1;i<=n-1;i++){ 63 scanf("%d%d",&u,&v); 64 link_p(u,v); 65 link_p(v,u); 66 } 67 for(register int i=1;i<=m;i++){ 68 scanf("%d%d",&u,&v); 69 link_q(u,v); 70 link_q(v,u); 71 } 72 } 73 74 void print(){ 75 for(int i=1;i<=m;i++) 76 printf("%d\n",q_edge[2*i].lca); 77 } 78 } 79 using namespace main_project; 80 81 int main(){ 82 scan(); 83 dfs(root); 84 print(); 85 }

?

轉載于:https://www.cnblogs.com/xhn2333/p/8760149.html

總結

以上是生活随笔為你收集整理的【模板】LCA的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。