poj2631树的直径

来源:互联网 发布:韩国人直播软件 编辑:程序博客网 时间:2024/05/16 10:51

Roads in the North
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 2920 Accepted: 1433
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
Source

The UofA Local 1999.10.16

#include <iostream>#include <stdio.h>#include <vector>#include <algorithm>#include <queue>using namespace std;const int N=12345;vector< pair<int,int> > vec[N];int dist[N];int vis[N];int sum;int pos;void bfs(int v0,int n){    for(int i=1;i<=n;i++){        dist[i]=0;        vis[i]=0;    }    vis[v0]=1;    pair<int,int> p,q,temp;    queue< pair<int,int> > que;    while(!que.empty()) que.pop();    p={v0,0};    que.push(p);    dist[v0]=0;    sum=0;    pos=v0;    while(!que.empty()){        temp=que.front();        que.pop();        for(int i=0;i<vec[temp.first].size();i++){            q=vec[temp.first][i];            if(!vis[q.first]){                dist[q.first]=dist[temp.first]+q.second;                vis[q.first]=1;                que.push(q);                if(dist[q.first]>sum){                    sum=dist[q.first];                    pos=q.first;                }            }        }    }}int main(){    int u,v,w;    int Max=0;    while(~scanf("%d %d %d",&u,&v,&w)){        vec[u].push_back(make_pair(v,w));        vec[v].push_back(make_pair(u,w));        Max=max(Max,max(u,v));    }    bfs(1,Max);    bfs(pos,Max);    printf("%d\n",sum);    return 0;}