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.
*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;
For each case only one integer represent the longest athletic track's length
1 7 1 2 20 2 3 10 2 4 20 4 5 10 5 6 10 4 7 40
80
题目给出了一棵生成树,问这棵生成树最长的路的长度是多少。
通过两次BFS可以得到答案。
原理: 设起点为u,第一次BFS找到的终点v一定是树的直径的一个端点
证明: 1) 如果u 是直径上的点,则v显然是直径的终点(因为如果v不是的话,则必定存在另一个点w使得u到w的距离更长,则于BFS找到了v矛盾)
2) 如果u不是直径上的点,则u到v必然于树的直径相交(反证),那么交点到v 必然就是直径的后半段了
所以v一定是直径的一个端点,所以从v进行BFS得到的一定是直径长度
#include<cstdio> #include<cstring> #include<queue> using namespace std; #define inf ((1<<20)-1) int n,maxx; int map[2005][2005],sum[2005]; bool flag[2005]; int bfs(int begin) { int temp,key; maxx=0; memset(flag,false,sizeof(flag)); queue<int> q; flag[begin]=true; q.push(begin); for(;!q.empty();) { temp=q.front(); for(int i=1;i<=n;++i) { if(map[temp][i]!=-1&&(!flag[i])) { flag[i]=true; q.push(i); sum[i]=sum[temp]+map[temp][i]; if(sum[i]>maxx) { maxx=sum[i]; key=i; } } } q.pop(); } return key; } int main() { int t,key; scanf("%d",&t); for(;t--;) { scanf("%d",&n); memset(map,-1,sizeof(map)); for(int i=1,j,k,dis;i<n;++i) { scanf("%d%d%d",&j,&k,&dis); map[j][k]=map[k][j]=dis; } sum[1]=0; key=bfs(1); sum[key]=0; key=bfs(key); printf("%d\n",maxx); } }