设s-t是这棵树的直径,那么对于任意给予的一点,它能够到达的最远的点是s或者t。
这样我们可以通过2次bfs找到树的直径了。
#include<cstdio> #include<queue> #include<cstring> #include<iostream> #include<algorithm> using namespace std; const int MAXN = 10010; struct node { int to; int v; int next; }edge[MAXN*2]; int p,len; int num[MAXN]; int vis[MAXN],pre[MAXN],ind,n; void add(int x,int y,int z) { edge[ind].to = y; edge[ind].v = z; edge[ind].next = pre[x]; pre[x] = ind ++; } void bfs(int s) { int i; queue<int>q; vis[s] = 1; memset(num,0,sizeof(num)); q.push(s); while(!q.empty()) { int temp = q.front(); q.pop(); for(i=pre[temp]; i!=-1; i=edge[i].next){ int t = edge[i].to; if(!vis[t]){ num[t] = num[temp] + edge[i].v; //cout<<num[t]<<endl; if(num[t] > len){ len = num[t]; p = t; } vis[t] = 1; q.push(t); } } } } int main() { //freopen("data.txt","r",stdin); int i,j; ind = 1; memset(pre,-1,sizeof(pre)); int x,y,z; while(~scanf("%d%d%d",&x,&y,&z)) { add(x,y,z); add(y,x,z); } memset(vis,0,sizeof(vis)); len = 0; bfs(1); //cout<<p<<endl; memset(vis,0,sizeof(vis)); len = 0; bfs(p); cout<<len<<endl; return 0; }