POJ 2631 -- Roads in the North【树的直径 && 裸题】

来源:互联网 发布:原创软件发布 编辑:程序博客网 时间:2024/05/23 00:04

Roads in the North
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 2358 Accepted: 1156

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

裸树的直径有木有!!!

#include <cstdio>#include <string>#include <cstring>#include <algorithm>#include <queue>#define maxn 40000+10#define maxm 80000+10using namespace std;int ed, sum;int dist[maxn], vis[maxn];int head[maxn], cnt;struct node {    int u, v, w, next;};node edge[maxm];void init(){    cnt = 0;    memset(head, -1, sizeof(head));}void add(int u, int v, int w){    edge[cnt] = {u, v, w, head[u]};    head[u] = cnt++;    edge[cnt] = {v, u, w, head[v]};    head[v] = cnt++;}void bfs(int sx){    queue<int>q;    memset(vis, 0, sizeof(vis));    memset(dist, 0, sizeof(dist));    ed = sx;    sum = 0;    vis[sx] = 1;    q.push(sx);    while(!q.empty()){        int u = q.front();        q.pop();        for(int i = head[u]; i != -1; i = edge[i].next){            int v = edge[i].v;            if(!vis[v]){                dist[v] = dist[u] + edge[i].w;                if(sum < dist[v]){                    ed = v;                    sum = dist[v];                }                vis[v] = 1;                q.push(v);            }        }    }}int main (){    int a, b, c;    init();    while(scanf("%d%d%d", &a, &b, &c) != EOF)        add(a, b, c);    bfs(1);    bfs(ed);    printf("%d\n", sum);    return 0;}


0 0