树的直径
#include<iostream> #include<cstdio> #include<cmath> #include<algorithm> #include<queue> #include<cstring> #define N 10010 using namespace std; struct node { int u,v,w,nxt; }e[N*2]; int first[N],cnt; void ade(int u,int v,int w) { e[++cnt].nxt=first[u]; first[u]=cnt; e[cnt].u=u; e[cnt].v=v; e[cnt].w=w; } int n,m; bool vis[N]; int dis[N]; void bfs(int x) { queue<int>q; q.push(x);vis[x]=1; while(!q.empty()) { int u=q.front(); q.pop(); for(int i=first[u];i;i=e[i].nxt) { int v=e[i].v; if(vis[v]) continue; dis[v]=dis[u]+e[i].w; vis[v]=1; q.push(v); } } } int maxx,pos; int main() { scanf("%d%d",&n,&m); for(int i=1,x,y,z;i<=m;i++) { scanf("%d%d%d",&x,&y,&z); ade(x,y,z); } bfs(1); for(int i=1;i<=n;i++) { if(maxx<dis[i]) { maxx=dis[i]; pos=i; } } //cout<<pos<<" "<<maxx<<endl; memset(dis,0,sizeof(dis)); memset(vis,0,sizeof(vis)); bfs(pos); int maxb=0,posb=0; for(int i=1;i<=n;i++) { if(maxb<dis[i]) { maxb=dis[i]; posb=i; } } //cout<<posb<<" "<<maxb; printf("%d",maxb); return 0; }