博客
关于我
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/

    你可能感兴趣的文章
    NN&DL4.1 Deep L-layer neural network简介
    查看>>
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.7 Parameters vs Hyperparameters
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    nnU-Net 终极指南
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>