题意:给一棵树求最长直径(数据见 POJ 1984)。
解题思路:两边bfs没什么说的。
Description
After hearing about the epidemic of obesity in the USA, Farmer John wants his cows to get more exercise, so he has committed to create a bovine marathon for his cows to run. The marathon route will include a pair of farms and a path comprised of a sequence of roads between them. Since FJ wants the cows to get as much exercise as possible he wants to find the two farms on his map that are the farthest apart from each other (distance being measured in terms of total length of road on the path between the two farms). Help him determine the distances between this farthest pair of farms.
Input
* Lines 1.....: Same input format as "Navigation Nightmare".
Output
* Line 1: An integer giving the distance between the farthest pair of farms.
Sample Input
7 6 1 6 13 E 6 3 9 E 3 5 7 S 4 1 3 N 2 4 20 W 4 7 2 S
Sample Output
52
Hint
The longest marathon runs from farm 2 via roads 4, 1, 6 and 3 to farm 5 and is of length 20+3+13+9+7=52.
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<cctype>
#include<list>
#include<iostream>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<vector>
using namespace std;
#define FOR(i, s, t) for(int i = (s) ; i <= (t) ; ++i)
#define REP(i, n) for(int i = 0 ; i < (n) ; ++i)
int buf[10];
inline long long read()
{
long long x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9')
{
if(ch=='-')f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9')
{
x=x*10+ch-'0';
ch=getchar();
}
return x*f;
}
inline void writenum(int i)
{
int p = 0;
if(i == 0) p++;
else while(i)
{
buf[p++] = i % 10;
i /= 10;
}
for(int j = p - 1 ; j >= 0 ; --j) putchar('0' + buf[j]);
}
/**************************************************************/
#define MAX_N 50000
const int INF = 0x3f3f3f3f;
queue<int> que;
int head[MAX_N << 1];
struct node
{
int to, w, next;
}edge[MAX_N << 1];
int top = 0;
int vis[MAX_N << 1];
int d[MAX_N << 1];
inline void init()
{
memset(head, -1, sizeof(head));
top = 0;
}
void add_edge(int u ,int v, int w)
{
edge[top].to = v;
edge[top].w = w;
edge[top].next = head[u];
head[u] = top++;
}
int bfs(int s)
{
memset(vis, 0, sizeof(vis));
memset(d, 0, sizeof(d));
while(!que.empty()) que.pop();
vis[s] = 1;
d[s] = 0;
que.push(s);
int dis = -1;
int ans = -1;
while(!que.empty())
{
int p = que.front();
que.pop();
for(int k = head[p] ; k != -1 ; k = edge[k].next)
{
int w = edge[k].w;
int to = edge[k].to;
if(!vis[to])
{
vis[to] = 1;
d[to] = d[p] + w;
if(d[to] > dis)
{
dis = d[to];
ans = to;
}
que.push(to);
}
}
}
return ans;
}
int main()
{
int n, m;
int u, v, w;
char ss[10];
while(~scanf("%d%d", &n, &m))
{
init();
for(int i = 0 ; i < m ;i++)
{
u = read();
v = read();
w = read();
scanf("%s", &ss);
add_edge(u, v, w);
add_edge(v, u, w);
}
int tmp = bfs(1);
int ans = bfs(tmp);
cout<<d[ans]<<endl;
}
return 0;
}