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


    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 }
  • 相关阅读:
    修改apache的默认访问目录
    禁止浏览器直接访问php文件
    使用Apache Bench进行压力测试
    关于mysql(或MariaDB)中的用户账号格式
    单表查询
    CSS设计指南之一 HTML标记与文档结构
    SQL SERVER技术内幕之10 可编程对象
    SQL SERVER技术内幕之10 事务并发
    观察者模式
    中介者模式
  • 原文地址:https://www.cnblogs.com/mjtcn/p/7291319.html
Copyright © 2020-2023  润新知