poj 2631 Roads in the North 【树的直径裸题】

Roads in the North
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 2350   Accepted: 1152

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


题意:求树的直径。。。裸的不能再裸了!


思路:两次BFS,第一次找S-T端点,第二次求树的直径。


AC代码:


#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
#define MAXN 10000+10
#define MAXM 100000000+10
using namespace std;
struct Edge
{
    int from, to, val, next;
};
Edge edge[MAXM];
int head[MAXN], edgenum;
int dist[MAXN];
bool vis[MAXN];
int node;//S-T路径的一个端点
int ans;//结果
void init()
{
    edgenum = 0;
    memset(head, -1, sizeof(head));
}
void addEdge(int u, int v, int w)
{
    Edge E = {u, v, w, head[u]};
    edge[edgenum] = E;
    head[u] = edgenum++;
}
int SPFA(int sx)
{
    queue<int> Q;
    memset(dist, 0, sizeof(dist));
    memset(vis, false, sizeof(vis));
    vis[sx] = true;
    Q.push(sx);
    node = sx; ans = 0;
    while(!Q.empty())
    {
        int u = Q.front();
        Q.pop();
        for(int i = head[u]; i != -1; i = edge[i].next)
        {
            Edge E = edge[i];
            if(!vis[E.to] && dist[E.to] < dist[u] + E.val)
            {
                dist[E.to] = dist[u] + E.val;
                vis[E.to] = true;
                Q.push(E.to);
                if(dist[E.to] > ans)
                {
                    ans = dist[E.to];
                    node = E.to;
                }
            }
        }
    }
}
void solve()
{
    SPFA(1);
    SPFA(node);
    printf("%d\n", ans);
}
int main()
{
    int a, b, c;
    init();
    while(scanf("%d%d%d", &a, &b, &c) != EOF)
    {
        addEdge(a, b, c);
        addEdge(b, a, c);
    }
    solve();
    return 0;
}


你可能感兴趣的:(poj 2631 Roads in the North 【树的直径裸题】)