POJ 1985 Cow Marathon

来源:互联网 发布:施工网络图绘制软件 编辑:程序博客网 时间:2024/05/22 06:23
Cow Marathon
Time Limit: 2000MS Memory Limit: 30000KTotal Submissions: 4088 Accepted: 2068Case Time Limit: 1000MS

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 61 6 13 E6 3 9 E3 5 7 S4 1 3 N2 4 20 W4 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 <cstdio>#include <cstring>#include <queue>#include <algorithm>#define MAXN 40000+10#define MAXM 80000+10using namespace std;struct Edge{int to, val, next;}edge[MAXM];int dist[MAXN];bool vis[MAXN];int head[MAXN], top;int N, M;int ans;int node;void init(){top = 0;memset(head, -1, sizeof(head));}void addEdge(int u, int v, int w){    edge[top].to=v;    edge[top].val=w;edge[top].next= head[u];head[u] = top++;}void getMap(){int a, b, c;char op[2];while(M--){scanf("%d%d%d%s", &a, &b, &c, op);addEdge(a, b, c);addEdge(b, a, c);} }void BFS(int sx){queue<int> Q;memset(dist, 0, sizeof(dist));memset(vis, 0, sizeof(vis));node = sx;ans = 0;vis[sx] = 1;Q.push(sx);while(!Q.empty()){int u = Q.front();Q.pop(); for(int i = head[u]; i != -1; i = edge[i].next){int v=edge[i].to;if(!vis[v]){dist[v] = dist[u] + edge[i].val;    vis[v] = 1;Q.push(v);} }}for(int i = 1; i <= N; i++){if(ans < dist[i]){ans = dist[i];node = i;}}}int main(){while(scanf("%d%d", &N, &M) != EOF){init();getMap();BFS(1);BFS(node); printf("%d\n", ans);}return 0;} 


0 0
原创粉丝点击