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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

树的直径模板

發布時間:2025/5/22 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 树的直径模板 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

代碼-樹的直徑

//solution dp #include<bits/stdc++.h> #define N 10010 using namespace std; struct Edge{int u,v,next,w; }G[N*2]; int tot=0,head[4*N],dp1[N],dp2[N]; //dp1[u]:從u出發到子樹內最長鏈//dp2[u]:從u出發,到與dp1不同的子樹中,產生的次長鏈 void addedge(int u,int v,int w){ G[++tot].u=u;G[tot].v=v;G[tot].w=w;G[tot].next=head[u];head[u]=tot; G[++tot].u=v;G[tot].v=u;G[tot].w=w;G[tot].next=head[v];head[v]=tot; }int ans=0; void work(int u,int fa){for (int i=head[u];i;i=G[i].next){int v=G[i].v,w=G[i].w;if (v==fa)continue;work(v,u);if (dp1[v]+w>dp1[u]){dp2[u]=dp1[u];dp1[u]=dp1[v]+w;}else dp2[u]=max(dp2[u],dp1[v]+w);} //找出以u為結點,在u的兩個不同子樹中的最長和次長鏈組合起來就是找出的直徑ans=max(dp1[u]+dp2[u],ans); //比較更新當前最長直徑}int main(){int n;read(n);for (int i=1;i<n;i++){int u,v,w;read(u);read(v);read(w);addedge(u,v,w);}work(1,0);printf("%d\n",ans);return 0;} //solution dfs #include<bits/stdc++.h> const int N=1000010; using namespace std; int n,m,head[N],tot,dis[N],cur,mx; struct Edge{int u,v,w,next;}G[N<<1];inline void addedge(int u,int v,int w){ G[++tot].u=u;G[tot].v=v;G[tot].w=w;G[tot].next=head[u];head[u]=tot; G[++tot].u=v;G[tot].v=u;G[tot].w=w;G[tot].next=head[v];head[v]=tot;}inline void dfs(int u,int fa){for(int i=head[u];i;i=G[i].next){int v=G[i].v;if(v==fa)continue;dis[v]=dis[u]+G[i].w; if(dis[v]>mx)cur=v,mx=dis[v];dfs(v,u);}} int main(){n=read();for(int i=1;i<n;i++){int u=read(),v=read(),w=read();addedge(u,v,w);}dfs(1,0);mx=0;memset(dis,0,sizeof(dis)); dfs(cur,0);printf("%d\n",mx); }

轉載于:https://www.cnblogs.com/Neworld2002/p/8461581.html

總結

以上是生活随笔為你收集整理的树的直径模板的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。