方法有很多,我这里用2种dfs的做法来做
方法:先从任意一点P出发,找离它最远的点Q,再从点Q出发,找离它最远的点W,W到Q的距离就是是的直径
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<stack>
using namespace std;
#define ll long long
const int maxn=2e5+5;
int d[maxn],head[maxn],f_num,ans,tot;
struct E{
int to,next,w;
}edge[maxn];
void add(int u,int v,int z){
edge[tot].to=v;
edge[tot].w=z;
edge[tot].next=head[u];
head[u]=tot++;
}
void dfs(int x,int fa){
if(ans<d[x]){
ans=d[x];
f_num=x;
}
for(int i=head[x];i!=-1;i=edge[i].next){
int v=edge[i].to;
if(v==fa) continue;
d[v]=d[x]+edge[i].w;
dfs(v,x);
}
}
int main(){
memset(head,-1,sizeof(head));
int n,m;cin>>n>>m;
for(int i=1;i<=m;i++){
int u,v,w;cin>>u>>v;
//cin>>w;
add(u,v,w);add(v,u,w);
}
dfs(1,0);
ans=0;
d[f_num]=0;
dfs(f_num,0);
cout<<ans<<endl;
}