消防

树上直径 + 尺取

考虑答案的路径一定是在树上直径,因为离树上任意一个点最远的点一定是直径的两个点其中之一

因此先 \(dfs\) 一下找出直径两个端点

从其中一个端点出发,尺取长度小于 \(s\) 的所有答案贡献即可

每次尺取的最远距离由三个部分组成:直径最开始那个端点到 \(l\) 的距离、直径最后那个端点到 \(r\) 的距离、\(l\)\(r\) 中间结点的次长距离

又不难发现每次 \(l\) 收缩一个位置的时候,删除掉的那个次长距离,一定小于 直径最开始那个端点到 \(l\) 的距离,因此不用考虑删那个次长距离,次长距离就一直维护最大值即可

复杂度是 \(O(n)\)

不知道为啥跑出来的耗时有种 \(O(nlogn)\) 的感觉,常数太大了,一定是 vector 惹的祸(不是

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
#include <array>
using namespace std;
#define pii pair<int, int>
vector<vector<array<int, 2>>>gra;
vector<vector<array<int, 3>>>dp;
vector<int>dis;

pii dfs1(int now, int pre)
{
    pii ans = {now, 0};
    for(auto [nex, w] : gra[now])
    {
        if(nex == pre) continue;
        auto [p, val] = dfs1(nex, now);
        val += w;
        if(val > ans.second) ans = {p, val};
    }
    return ans;
}

void dfs2(int now, int pre)
{
    for(auto [nex, w] : gra[now])
    {
        if(nex == pre) continue;
        dis[nex] = dis[now] + w;
        dfs2(nex, now);
        auto x = dp[nex][0];
        x[0] += w;
        x[1] = nex;
        x[2] = w;
        if(x > dp[now][0]) swap(x, dp[now][0]);
        if(x > dp[now][1]) swap(x, dp[now][1]);
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n, s;
    cin >> n >> s;
    gra.resize(n + 1);
    dp.resize(n + 1, vector<array<int, 3>>(2, {0, 0}));
    dis.resize(n + 1, 0);
    for(int i=1; i<n; i++)
    {
        int a, b, c;
        cin >> a >> b >> c;
        gra[a].push_back({b, c});
        gra[b].push_back({a, c});
    }
    auto ax = dfs1(1, 1);
    int u = ax.first;
    dfs2(u, u);
    int maxx = 0;
    for(int now : dis) maxx = max(maxx, now);
    int l = u, r = u, now = 0, nex = maxx, ans = maxx;
    while(l)
    {
        while(dp[r][0][1] && dis[dp[r][0][1]] - dis[l] <= s)
        {
            r = dp[r][0][1];
            nex = maxx - dis[r];
            now = max(now, dp[r][1][0]);
        }
        ans = min(ans, max({dis[l], nex, now}));
        l = dp[l][0][1];
    }
    cout << ans << endl;
    return 0;
}

原文地址:http://www.cnblogs.com/dgsvygd/p/16867902.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性