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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

洛谷 3398 仓鼠找sugar 【模板】判断树上两链有交

發(fā)布時間:2024/4/17 编程问答 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 洛谷 3398 仓鼠找sugar 【模板】判断树上两链有交 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

【題解】

  題意就是判斷樹上兩條鏈是否有交??谠E是“判有交,此鏈有彼祖”。即其中一條鏈的端點的Lca在另一條鏈上。

  我們設(shè)兩條鏈的端點的Lca中深度較大的為L2,對L2與另一條鏈的兩個端點分別求Lca,若滿足其中一個Lca等于L2,即表示兩鏈有交。

  

1 #include<cstdio> 2 #include<algorithm> 3 #include<cstring> 4 #define LL long long 5 #define rg register 6 #define N 500010 7 using namespace std; 8 int n,m,tot,last[N],siz[N],fa[N],dep[N],hvy[N],top[N]; 9 struct edge{ 10 int to,pre; 11 }e[N<<1]; 12 inline int read(){ 13 int k=0,f=1; char c=getchar(); 14 while(c<'0'||c>'9')c=='-'&&(f=-1),c=getchar(); 15 while('0'<=c&&c<='9')k=k*10+c-'0',c=getchar(); 16 return k*f; 17 } 18 void dfs1(int x){ 19 siz[x]=1; dep[x]=dep[fa[x]]+1; 20 for(rg int i=last[x],to;i;i=e[i].pre)if((to=e[i].to)!=fa[x]){ 21 fa[to]=x; dfs1(to); siz[x]+=siz[to]; 22 if(siz[to]>siz[hvy[x]]) hvy[x]=to; 23 } 24 } 25 void dfs2(int x,int tp){ 26 top[x]=tp; 27 if(hvy[x]) dfs2(hvy[x],tp); 28 for(rg int i=last[x],to;i;i=e[i].pre)if((to=e[i].to)!=fa[x]&&to!=hvy[x]) 29 dfs2(to,to); 30 } 31 inline int lca(int x,int y){ 32 int t1=top[x],t2=top[y]; 33 while(t1!=t2){ 34 if(dep[t1]<dep[t2]) swap(t1,t2),swap(x,y); 35 x=fa[t1]; t1=top[x]; 36 } 37 return dep[x]<dep[y]?x:y; 38 } 39 int main(){ 40 n=read(); m=read(); 41 for(rg int i=1;i<n;i++){ 42 int u=read(),v=read(); 43 e[++tot]=(edge){v,last[u]}; last[u]=tot; 44 e[++tot]=(edge){u,last[v]}; last[v]=tot; 45 } 46 dfs1(1); dfs2(1,1); 47 while(m--){ 48 int a=read(),b=read(),x=read(),y=read(); 49 int L1=lca(a,b),L2=lca(x,y); 50 if(dep[L1]>dep[L2]) swap(L1,L2),swap(a,x),swap(b,y); 51 puts(lca(L2,a)==L2||lca(L2,b)==L2?"Y":"N"); 52 } 53 return 0; 54 } View Code

?

  

轉(zhuǎn)載于:https://www.cnblogs.com/DriverLao/p/9301130.html

總結(jié)

以上是生活随笔為你收集整理的洛谷 3398 仓鼠找sugar 【模板】判断树上两链有交的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

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