博客
关于我
2019牛客国庆集训派对day4H题
阅读量:653 次
发布时间:2019-03-15

本文共 995 字,大约阅读时间需要 3 分钟。

新建一棵树,边权等于原树中(u, v)的唯一路径距离,目标是最大化新树的总成本。

首先,确定原树的直径。直径是指树中延伸最远的简单路径。寻找直径的两个端点可以使用三次DFS:

  • 从任意节点出发,进行DFS,记录每个节点到起点的最远距离。
  • 在第一步中的最远节点作为起点,进行DFS,记录每个节点到该节点的最远距离。
  • 这两个最远节点即为原树的直径端点。
  • 接下来,计算直径端点到其它所有节点的距离之和,即为新树的最大成本。

    最佳做法是三次DFS:

    #include 
    #include
    using namespace std;vector
    > G[maxn];vector
    visited;ll dist = -1e18;int point;ll res[maxn];void dfs(int x, bool update, int index) { if (update) { if (G[x].size() > dist) dist = G[x].size(); point = x; } for (int v : G[x]) { if (!visited[v]) { visited[v] = true; if (!update) res[index][v] = res[index][x] + G[x][v]; else if (dist <= res[index][x] + G[x][v]) { res[index][v] = res[index][x] + G[x][v]; dist = res[index][v]; } dfs(v, update, index); } }}

    需要注意的是,优化代码时应保留所有必要的变量和结构,确保程序正确工作。完成三次DFS后,点point即为终点,dist记录原树的直径长度。

    最终,计算步骤即为从两个端点出发的总距离和,得到为新树的最大成本。

    转载地址:http://pzfmz.baihongyu.com/

    你可能感兴趣的文章
    NoSQL&MongoDB
    查看>>
    NoSQL介绍
    查看>>
    NoSQL数据库概述
    查看>>
    Notadd —— 基于 nest.js 的微服务开发框架
    查看>>
    NOTE:rfc5766-turn-server
    查看>>
    Notepad ++ 安装与配置教程(非常详细)从零基础入门到精通,看完这一篇就够了
    查看>>
    Notepad++在线和离线安装JSON格式化插件
    查看>>
    notepad++最详情汇总
    查看>>
    notepad++正则表达式替换字符串详解
    查看>>
    notepad如何自动对齐_notepad++怎么自动排版
    查看>>
    Notes on Paul Irish's "Things I learned from the jQuery source" casts
    查看>>
    Notification 使用详解(很全
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    NotImplementedError: Could not run torchvision::nms
    查看>>
    nova基于ubs机制扩展scheduler-filter
    查看>>
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>
    nowcoder—Beauty of Trees
    查看>>
    np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
    查看>>
    np.power的使用
    查看>>
    NPM 2FA双重认证的设置方法
    查看>>