Cow Marathon

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. 

这道题刚开始我用的是cin那个输入,但是会时间超限。改为scanf之后就AC了。下次要注意这个。

/*
    此题求的是树的最长链, 要注意此题不能用dis[maxn][maxn]来记录a, b两点的距离,这样会超空间,
	 也就是超内存,要用另一种储存方式储存。此题思想很简单, 随便选一个点,搜此点能到的最远距离, 
	 并记录最远距离的点, 然后再从最远距离的点搜这点能到的最远距离, 这个dis就是答案。
		在听说美国肥胖流行之后,农夫约翰希望自己的奶牛多锻炼身体,所以他决心为自己的奶牛创造一个牛马拉松。
	 马拉松路线将包括一对农场和一条由一系列道路组成的路径。 由于FJ希望母牛尽可能多地运动,
	 他希望在他的地图上找到彼此距离最远的两个农场(距离以两个农场之间的道路总长度来衡量)。
	  帮助他确定这个最远的一对农场之间的距离。
*/
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<vector>

using namespace std;

const int maxn = 100020;
int dis[maxn], ans;
bool vis[maxn];
vector<pair<int, int> > v[maxn];

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;
		}
		pair <int, int> t;
		for (int i = 0; i < v[F].size(); i++){
			t = v[F][i];
			if (vis[t.first] == 0){
				vis[t.first] = 1;
				dis[t.first] = dis[F] + t.second;
				Q.push(t.first);
			}
		}
	}
	return point;
}

int main()
{
	int x, y, z; char s;
	int n, m;
	scanf ("%d %d", &n, &m);
	while(m --){
//		cin >> x >> y >> z >> s;
		scanf ("%d %d %d %c", &x, &y, &z, &s);
		v[x].push_back(make_pair(y, z));
		v[y].push_back(make_pair(x, z));
	}
	ans = 0;
	int point = BFS(1);
	ans = 0;
	BFS(point);
	cout << ans << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/hqzzbh/article/details/81414791