The longest athletic track 求树的直径
After a long time of algorithm training, we want to hold a running contest in our beautiful campus. Because all of us are curious about a coders's fierce athletic contest,so we would like a more longer athletic track so that our contest can last more .
In this problem, you can think our campus consists of some vertexes connected by roads which are undirected and make no circles, all pairs of the vertexes in our campus are connected by roads directly or indirectly, so it seems like a tree, ha ha.
We need you write a program to find out the longest athletic track in our campus. our athletic track may consist of several roads but it can't use one road more than once.

Input
*Line 1: A single integer: T represent the case number T <= 10
For each
case
*Line1: N the number of vertexes in our campus 10 <= N <=
2000
*Line2~N three integers a, b, c represent there is a road between vertex
a and vertex b with c meters long
1<= a,b <= N, 1<= c <=
1000;
Output
For each case only one integer represent the longest athletic track's length
Sample Input
1 7 1 2 20 2 3 10 2 4 20 4 5 10 5 6 10 4 7 40
Sample Output
80
#include <iostream> #include <cstring> #include <queue> using namespace std; const int inf = 10000000; const int maxn = 2005; int G[maxn][maxn],sum[maxn]; bool flag[maxn]; int maxd,k; int T,N; queue<int> que; void bfs(int begain) { while(!que.empty()) que.pop(); memset(flag,false,sizeof(flag)); que.push(begain); flag[begain]=true; maxd = 0; while(!que.empty()) { int cur = que.front(); que.pop(); for(int i=1;i<=N;i++) { if(!flag[i]&&G[cur][i]!=inf) { sum[i]=sum[cur]+G[cur][i]; que.push(i); flag[i]=true; if(sum[i]>maxd) { maxd=sum[i]; k = i; } } } } } int main() { cin >> T; while(T--) { cin >> N; for(int i=1;i<=N;i++) { for(int j=1;j<=N;j++) G[i][j]=inf; G[i][i]=1; } int from,to,w; for(int i=1;i<N;i++) { cin >> from >> to >> w; G[from][to]=G[to][from]=w; } sum[1]=0; bfs(1); sum[k]=0; bfs(k); cout << maxd << endl; } return 0; }

浙公网安备 33010602011771号