Cow Marathon(BFS求数的直径)

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. 

题意:有N个农田以及M条路,给出M条路的长度以及路的方向(这道题不影响,用不到),让你找到一条 两农田(任意的)间的路径,使得距离最长,并输出最长距离。

思路:就是求树的直径。第一次BFS找最长路径的一个端点,第二次BFS求最长距离。

#include <iostream>
#include<cstdio>
#include<queue>
#include<string.h>
#define N 50000 
using namespace std;
struct st
{
	int from,to,val,next;
}edge[2*N];
int dis[N];
bool vis[N];
int head[N];
int n,m;
int ans,num;
int toned;//最长路的端点

void add(int u,int v,int w)
{
	edge[num].from=u;
	edge[num].to=v;
	edge[num].val=w;
	edge[num].next=head[u];
	head[u]=num++;
}

void BFS(int s)
{
	memset(vis,0,sizeof(vis));
	memset(dis,0,sizeof(dis));
	queue<int>q;
	q.push(s);
	vis[s]=1;
	ans=0;
	while(!q.empty())
	{
		int u,v,i;
		u=q.front();
		q.pop();
		for(i=head[u];i!=-1;i=edge[i].next)
		{
			v=edge[i].to;
			if(!vis[v])
			{
				if(dis[v]<dis[u]+edge[i].val)
				dis[v]=dis[u]+edge[i].val;
				vis[v]=1;
				q.push(v);
			}
		 } 
	}
	for(int i=1;i<=n;i++)
	{
		if(ans<dis[i])
		{
			ans=dis[i];
			toned=i;
		}
	}
}
int main(){
	int u,v,w;
	char c[2];
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		num=1;
		memset(head,-1,sizeof(head));
		for(int i=0;i<m;i++)
		{
			scanf("%d%d%d%s",&u,&v,&w,c);
			add(u,v,w);
			add(v,u,w);
		}
		BFS(1);
		BFS(toned);
		printf("%d\n",ans);
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/weixin_41988545/article/details/81391751