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

本文介绍了一个经典的图论问题——求解北境村落间最大距离,即树的直径问题。通过两次广度优先搜索(BFS),首先找到离起点最远的节点,再以此节点为起点再次进行搜索,从而高效地找出两最远村落间的距离。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值