Cow Marathon(BFS求數的直徑)

十二分熱愛發表於2018-08-03

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;
} 

 

相關文章