跳到正文

题解

CF1004E题解

yimuhua约 3 分钟
原文
文章信息与版本

文章信息

发布
2023年1月29日
收录
2025年12月19日
更新
2026年11月11日
篇幅
约 3 分钟
题目
CF1004E

版本

  1. v1当前

显然最优解一定在直径上,且尽量长。

证明:

若存在一个最大值更小的分支,这个分支的大小一定不比解在直径上时小。同理,我们想让这条路径尽量长。

于是尺取直径上的一条链,其到直径上所有点的最长距离一定为其到直径两端点的距离的较大值。对于不在这条直径上的点可以直接搜索,它只会被它的祖先中离它最近的、在直径上的点搜索,于是时间复杂度为 O(n)O(n)。

代码:

C++
#include <bits/stdc++.h>
using namespace std;
struct node {
    int x, w;
};
bool vis[100005];
vector<node> v[100005];
int n, s, p, ans = 1e9, fa[100005], dis[100005], dep[100005];
void dfs(int x, int fa) {
    ::fa[x] = fa, dep[x] = dep[fa] + 1;
    if(dis[x] > dis[p])
        p = x;
    for(auto i : v[x])
        if(i.x != fa && !vis[i.x])
            dis[i.x] = dis[x] + i.w, dfs(i.x, x);
    return;
}
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> s;
    for(int i = 1, x, y, w; i < n; i++)
        cin >> x >> y >> w, v[x].push_back((node){y, w}), v[y].push_back((node){x, w});
    dfs(dis[1] = 1, 0), dis[p] = 0, dfs(p, 0);
    for(int i = p, j = p, x; i; i = fa[i]) {
        while(dep[j] - dep[i] >= s)
            j = fa[j];
        x = max(dis[p] - dis[j], dis[i]), ans = min(ans, x);
    }
    for(int i = p; i; i = fa[i])
        vis[i] = 1;
    for(int i = p; i; i = fa[i])
        dis[p = i] = 0, dfs(i, fa[i]);
    for(int i = 1; i <= n; i++)
        ans = max(ans, dis[i]);
    cout << ans;
    return 0;
}
原文
存档评论2 条抓取于