Roads in the North

来源:互联网 发布:校园网mac地址修改 编辑:程序博客网 时间:2024/05/01 23:09
Roads in the North
Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%lld & %llu

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 61 4 56 3 92 6 86 1 7

Sample Output

22

/*
题意:
有10000个村庄,有很多条路,现在这些路已经把村庄都连了起来,求最远的两个村庄的路的距离。

思路,把每一边都历遍一下,找到两个距离最远的村庄。

这里有一个结论,在图中,要找到距离最远的两点,先随便从一个点入手BFS,找到距离这个点最远的点,在从这个点BFS找到距离这点最远的点,这两点之间的距离就是这棵树的直径。所以直接进行BFS搜索就行了。

#include<cstdio>#include<queue>#include<string.h>#define M 100000using namespace std;int m,ans,flag[M],sum[M],n,a,b,c,i,head[M],num,node;struct stu{    int from,to,val,next;}st[M];void init(){    num=0;    memset(head,-1,sizeof(head));}void add_edge(int u,int v,int w){    st[num].from=u;    st[num].to=v;    st[num].val=w;    st[num].next=head[u];    head[u]=num++;}void bfs(int fir){        ans=0;    int u;    memset(sum,0,sizeof(sum));    memset(flag,0,sizeof(flag));    queue<int>que;    que.push(fir);    flag[fir]=1;    while(!que.empty())    {       u=que.front();       que.pop();       for(i = head[u] ; i != -1 ; i=st[i].next)       {           if(!flag[st[i].to] && sum[st[i].to] < sum[u]+st[i].val)           {               sum[st[i].to]=sum[u]+st[i].val;               if(ans < sum[st[i].to])               {                   ans=sum[st[i].to];                   node=st[i].to;               }               flag[st[i].to]=1;               que.push(st[i].to);            }        }    }}int main(){        init();    while(scanf("%d %d %d",&a,&b,&c)!=EOF)    {        add_edge(a,b,c);        add_edge(b,a,c);    }           bfs(1);       bfs(node);       printf("%d\n",ans);}
0 0