POJ 1985 Cow Marathon【树的直径】

POJ 1985 Cow Marathon

总时间限制: 

2000ms

单个测试点时间限制: 

1000ms

内存限制: 

65536kB

描述

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.

输入

* Lines 1.....: Same input format as "Navigation Nightmare".

输出

* Line 1: An integer giving the distance between the farthest pair of farms.

样例输入

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

样例输出

52

提示

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.

-------------------------

最后的字母是没什么用的~~

//POJ 1985
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
#include <queue>
using namespace std;
 
const int N = 50000;
struct Node
{
	int to,value;
};
vector<Node> v[N];
int vis[N],dis[N];
int ans;
 
int BFS(int x)
{
	memset(dis,0,sizeof(dis));
	memset(vis,0,sizeof(vis));
	queue<int> q;
	q.push(x);
	vis[x]=1;
	int point = 0;
	while(!q.empty())
	{
		int f=q.front();
		q.pop();
		if(dis[f]>ans)
		{
			ans = dis[f];
			point = f;
		}
		Node tmp; 
		for(int i=0;i<v[f].size();i++)
		{
			tmp = v[f][i];
			if(vis[tmp.to]==0)
			{
				vis[tmp.to]=1;
				dis[tmp.to] = dis[f] + tmp.value;
				q.push(tmp.to);
			}
		}
	}
	return point;
}
int main()
{
	int n,m;
	while(~scanf("%d%d",&n,&m))
	{
		for(int i=0;i<=n;i++)
			v[i].clear();
		for(int i=0;i<m;i++)
		{
			int x,y,z;
			char c;
			scanf("%d %d %d %c",&x,&y,&z,&c);
			v[x].push_back((Node){y,z});
			v[y].push_back((Node){x,z});
		}
		ans = 0;
		int point = BFS(1);
		ans = 0;
		BFS(point);
		
		printf("%d\n",ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/tingtingyuan/article/details/81412326