http://lightoj.com/login_main.php?url=volume_showproblem.php?problem=1094
Given a tree (a connected graph with no cycles), you have to find the farthest nodes in the tree. The edges of the tree are weighted and undirected. That means you have to find two nodes in the tree whose distance is maximum amongst all nodes.
Input
Input starts with an integer T (≤ 10), denoting the number of test cases.
Each case starts with an integer n (2 ≤ n ≤ 30000) denoting the total number of nodes in the tree. The nodes are numbered from 0 to n-1. Each of the next n-1 lines will contain three integers u v w (0 ≤ u, v < n, u ≠ v, 1 ≤ w ≤ 10000) denoting that node u and v are connected by an edge whose weight is w. You can assume that the input will form a valid tree.
Output
For each case, print the case number and the maximum distance.
Sample Input
2
4
0 1 20
1 2 30
2 3 50
5
0 2 20
2 1 10
0 3 29
0 4 50
Sample Output
Case 1: 100
Case 2: 80
#include<iostream>
#define MAXN 1010000
#include<vector>
#include<cstdio>
#include<string.h>
using namespace std;
struct Edge
{
int w;
int v;
Edge(int vv,int ww):v(vv),w(ww){}
};
int n,m;
int dist[MAXN],max_len,End;
vector<vector<Edge> >G;
void dfss(int u,int father,int len)
{
if(len>max_len)max_len=len,End=u;
for(int i=0; i<G[u].size(); i++)
{
int v=G[u][i].v,w=G[u][i].w;
if(v==father)continue;
dist[v]=max(dist[v],len+w);
dfss(v,u,len+w);
}
}
int main()
{
int u,v,w,t,num=0;
cin>>t;
while(t--)
{
num++;
cin>>n;
m=n-1;
G.clear();
G.resize(n+1);
for(int i=1; i<=m; i++)
{
scanf("%d%d%d",&u,&v,&w);
G[u].push_back(Edge(v,w));
G[v].push_back(Edge(u,w));
}
memset(dist,0,sizeof(dist));
max_len=0;
dfss(1,-1,0);//第一次深搜找到距离某点最远的点op
dfss(End,-1,0);//求距离op最远的点,两次深搜求出直径;
int ans=0;
cout<<"Case "<<num<<":"<<" ";
cout<<dist[End]<<endl;
}
return 0;
}