日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

树的直径模板

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

代碼-樹的直徑

//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

總結

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

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