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.
树的直径 : 一个图中,任意两个点之间 路径最长的距离
两个bfs ,第一个bfs 求的是 最长距离的一个端点,然后再以这个点为起点求一次bfs 找到最长距离。
代码
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<vector>
#include<set>
#define CLR(a,b) memset((a),(b),sizeof(a))
#define inf 0x3f3f3f3f
#define mod 100009
#define LL long long
#define MAXN 1000+10
#define MAXM 2000000+100
#define ll o<<1
#define rr o<<1|1
#define lson o<<1,l,mid
#define rson o<<1|1,mid+1,r
using namespace std;
void read(int &x){
x=0;char c;
while((c=getchar())<'0');
do x=x*10+c-'0';while((c=getchar())>='0');
}
struct Edge {
int from,to,val,next;
}edge[MAXM];
int head[MAXN],top;
int dist[MAXN]; // 距离
int vis[MAXN];
int n,m;
int ans,node;
void addedge(int a,int b,int c)
{
Edge e={a,b,c,head[a]};
edge[top]=e;head[a]=top++;
}
void init()
{
memset(head,-1,sizeof(head));
top=0;
}
void getmap()
{
while(m--)
{
int a,b,c;
cin>>a>>b>>c;
addedge(a,b,c);
addedge(b,a,c);
}
}
void bfs(int st)
{
queue<int>Q;
memset(vis,0,sizeof(vis));
memset(dist,0,sizeof(dist));
Q.push(st); vis[st]=1;
while(!Q.empty())
{
int now=Q.front();Q.pop();
for(int i=head[now];i!=-1;i=edge[i].next)
{
Edge e=edge[i];
if(!vis[e.to])
{
dist[e.to]=dist[now]+e.val;
vis[e.to]=1;
Q.push(e.to);
}
}
}
ans=0;node=st;
for(int i=1;i<=n;i++)
{
if(dist[i]>ans)
{
ans=dist[i];
node=i;
}
}
}
void solve()
{
bfs(1);
bfs(node);
printf("%d\n",ans);
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
init();
getmap();
solve();
}
return 0;
}