The diameter of the tree is the length of the longest path in the tree.
Two DFS requests are used to obtain the farthest point P from any point for the first time,
The second time we get the farthest point from P, this path is the longest path, that is, the longest path.
#include <iostream>#include <cstring>#include <string>#include <cstdio>#include <cmath>#include <algorithm>#include <vector>#include <queue>#include <map>#define inf 0x3f3f3f3f#define eps 1e-6#define ll __int64using namespace std;struct node{ int v,w,next;}e[80010];int n,m,ans,p,h,head[40010],vis[40010];void addedge(int a,int b ,int c){ e[h].v=b; e[h].w=c; e[h].next=head[a]; head[a]=h++;}void init(){ memset(head,-1,sizeof head); h=0;}void dfs(int x,int num){ vis[x]=1; if(num>ans) ans=num,p=x; for(int i=head[x];i!=-1;i=e[i].next) { if(!vis[e[i].v]) dfs(e[i].v,num+e[i].w); }}int main(){ int a,b,c; char s[10]; while(~scanf("%d%d",&n,&m)) { init(); while(m--) { scanf("%d%d%d%s",&a,&b,&c,s); addedge(a,b,c); addedge(b,a,c); } ans=0; memset(vis,0,sizeof vis); dfs(1,0); memset(vis,0,sizeof vis); dfs(p,0); printf("%d\n",ans); } return 0;}