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

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

时间:2015-08-17 19:39:57      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:

Roads in the North
Time Limit: 1000MS   Memory Limit: 65536K
Total 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 6
1 4 5
6 3 9
2 6 8
6 1 7

Sample Output

22

裸树的直径有木有!!!

#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <queue>
#define maxn 40000+10
#define maxm 80000+10
using 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;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

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

标签:

原文地址:http://blog.csdn.net/hpuhjh/article/details/47728449

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