首页 > 其他分享 >洛谷-P2491 消防

洛谷-P2491 消防

时间:2022-11-07 23:47:15浏览次数:66  
标签:include 洛谷 消防 int nex P2491 now dp dis

消防

树上直径 + 尺取

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

因此先 \(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;
}

标签:include,洛谷,消防,int,nex,P2491,now,dp,dis
From: https://www.cnblogs.com/dgsvygd/p/16867902.html

相关文章