poj1985 Cow Marathon (求树的直径)
Cow Marathon
Time Limit: 2000MS | Memory Limit: 30000K | |
Total Submissions: 3195 | Accepted: 1596 | |
Case 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 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.
Source
求树的直径:两遍bfs。
1.随便找一个点进行第一遍bfs,可以保证最远的点一定是树的直径的一个端点,
2.以第一遍bfs找到的树的直径的端点为起点,进行第二遍bfs,找到另一个端点,它们之间的距离就是树的直径。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <cmath> 6 using namespace std; 7 const int N = 40005; 8 int n,m; 9 int head[N]; 10 struct node { 11 int v,w,next; 12 }edge[N<<1]; 13 int cnt; 14 void add(int u, int v, int w) { 15 edge[cnt].v = v; 16 edge[cnt].w = w; 17 edge[cnt].next = head[u]; 18 head[u] = cnt++; 19 } 20 int vis[N]; 21 int dist[N]; 22 int que[N]; 23 int ret; 24 int bfs(int u) { 25 memset(vis, 0, sizeof(vis)); 26 int start = 0; 27 int rear = 1; 28 que[1] = u; 29 vis[u] = 1; 30 dist[u] = 0; 31 int i; 32 int ans = 0; 33 while (start < rear) { 34 start++; 35 int tmp = que[start]; 36 for (i = head[tmp]; i != -1; i = edge[i].next) { 37 int v = edge[i].v; 38 if (!vis[v]) { 39 rear++; 40 que[rear] = v; 41 vis[v] = 1; 42 dist[v] = dist[tmp] + edge[i].w; 43 if (dist[v] > ans) { 44 ans = dist[v]; 45 ret = v; 46 } 47 } 48 } 49 } 50 return ans; 51 } 52 int main() { 53 // freopen("in.txt","r",stdin); 54 int i; 55 int u,v,w; 56 char ch; 57 while (scanf("%d %d",&n,&m) != EOF) { 58 memset(head, -1, sizeof(head)); 59 cnt = 0; 60 for (i = 0; i < m; i++) { 61 scanf("%d %d %d %c",&u,&v,&w,&ch); 62 add(u,v,w); 63 add(v,u,w); 64 } 65 bfs(1); 66 printf("%d\n",bfs(ret)); 67 } 68 return 0; 69 }
posted on 2013-08-21 10:46 shijianupc 阅读(254) 评论(0) 编辑 收藏 举报