Roads in the North (裸的求树直径)

Roads in the North

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

题目链接:https://cn.vjudge.net/contest/242149#problem/J

题目就是让你求最远两个村庄之间的距离,很明显的求树的直径(如果能读懂题的话,我一般谷歌走一波)。树的直径的求解方法也就是一个模板啊,任意找一个点进行一次bfs(一般选第一个点),然后找到离他最远的一个点,再对该点进行一次bfs就能求得答案了。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
using namespace std;
const int maxn = 3e4+5;

int head[maxn], book[maxn], dis[maxn];
int start;

struct edge
{
    int to, w, ne;
}e[maxn];
int cnt = 1;    //这里我是有一部分想多了,所以才这样写的,还给自己挖了个坑,因为我刚开始初始化为0,一直报错,是存边和取边没有对应,读者别和我一样弱智。

void init()
{
    memset(dis, 0, sizeof(dis));
    memset(book, 0, sizeof(book));
}

void add(int a, int b, int w)
{
    e[cnt].to = b;
    e[cnt].w = w;
    e[cnt].ne = head[a];
    head[a] = cnt++;
}

void bfs(int s)
{
    init();
    queue<int> q;
    q.push(s);
    book[s] = 1;    dis[s] = 0;
    while(q.size())
    {
        int temp = q.front();
        q.pop();
        for(int i = head[temp]; i; i = e[i].ne)
        {
            if(book[e[i].to] || dis[e[i].to] >= e[i].w+dis[temp])   continue ;
            dis[e[i].to] = e[i].w+dis[temp];
            q.push(e[i].to);
            book[e[i].to] = 1;
        }
    }
    int _max = -1;
    for(int i = 1; i < maxn; i++)
        if(dis[i] > _max)
        {
            _max = dis[i];
            start = i;
        }
}

int main()
{
    int x, y, z;
    memset(head, 0, sizeof(head));
    while(~scanf("%d%d%d", &x, &y, &z))
    {
        add(x, y, z);
        add(y, x, z);
    }
    bfs(1);
    bfs(start);
    printf("%d\n", dis[start]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40788897/article/details/81290066
今日推荐