码迷,mamicode.com
首页 > 其他好文 > 详细

poj2631 ?Roads in the North(求树的直径)

时间:2017-08-05 21:11:53      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:poj2631   between   bfs   front   limit   esc   each   seq   push   

 

Roads in the North

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 2941   Accepted: 1447

Description

Building and maintaining roads among communities in the far North is an expensive business. With this in mind, the roads are build such that there is only one route from a village to a village that does not pass through some other village twice. 
Given is an area in the far North comprising a number of villages and roads among them such that any village can be reached by road from any other village. Your job is to find the road distance between the two most remote villages in the area. 

The area has up to 10,000 villages connected by road segments. The villages are numbered from 1. 

Input

Input to the problem is a sequence of lines, each containing three positive integers: the number of a village, the number of a different village, and the length of the road segment connecting the villages in kilometers. All road segments are two-way.

Output

You are to output a single integer: the road distance between the two most remote villages in the area.

Sample Input

5 1 6
1 4 5
6 3 9
2 6 8
6 1 7

Sample Output

22

code

 1 #include<cstdio>
 2 #include<queue>
 3 #include<algorithm>
 4 #include<cstring>
 5 
 6 using namespace std;
 7 
 8 const int MAXN = 10010;
 9 
10 struct Edge{
11     int to,w,nxt;
12     Edge(){}
13     Edge(int x,int y,int z){to = x,w = y,nxt = z;}
14 }e[500100];
15 
16 int head[MAXN<<1],dis[MAXN];
17 int tot;
18 queue<int>q;
19 
20 int bfs(int x)
21 {
22     memset(dis,-1,sizeof(dis));
23     q.push(x);
24     dis[x] = 0;
25     int id,mx = 0;
26     
27     while (!q.empty())
28     {
29         int u = q.front();
30         q.pop();
31         for (int i=head[u]; i; i=e[i].nxt)
32         {
33             int v = e[i].to, w = e[i].w;
34             if (dis[v]==-1)    //双向边,只算一次 
35             {
36                 dis[v] = dis[u]+w;
37                 if (dis[v]>mx) mx = dis[v],id = v;
38                 q.push(v);
39             }
40         }
41     }
42     return id;
43 }
44 int main()
45 {
46     int u,v,w;
47     while (scanf("%d%d%d",&u,&v,&w)!=EOF)
48     {
49         e[++tot] = Edge(v,w,head[u]);
50         head[u] = tot;
51         e[++tot] = Edge(u,w,head[v]);
52         head[v] = tot;
53     }
54     printf("%d",dis[bfs(bfs(1))]);    
55     return 0;
56 }

 

poj2631 ?Roads in the North(求树的直径)

标签:poj2631   between   bfs   front   limit   esc   each   seq   push   

原文地址:http://www.cnblogs.com/mjtcn/p/7291319.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!