Leetcode—2646.最小化旅行的价格总和【困难】

2023每日刷题(五十三)

Leetcode---2646.最小化旅行的价格总和

算法思想

看灵神的

实现代码

cpp 复制代码
class Solution {
public:
    int minimumTotalPrice(int n, vector<vector<int>>& edges, vector<int>& price, vector<vector<int>>& trips) {
        vector<int> g[n];
        for(auto e: edges) {
            int start = e[0], end = e[1];
            g[start].emplace_back(end);
            g[end].emplace_back(start);
        }
        vector<int> cnt(n);
        for(auto t: trips) {
            int end = t[1];
            function<bool(int, int)> dfs = [&](int x, int fa) {
                if(x == end) {
                    cnt[x]++;
                    return true;
                }
                for(auto y: g[x]) {
                    if(y != fa && dfs(y, x)) {
                        cnt[x]++;
                        return true;
                    }
                }
                return false;
            };
            dfs(t[0], -1);
        }
        function<pair<int, int>(int, int)> dfs2 = [&](int x, int fa) -> pair<int, int> {
            int not_half = price[x] * cnt[x];
            int half = not_half / 2;
            for(auto y: g[x]) {
                if(y != fa) {
                    auto [nh, h] = dfs2(y, x);
                    // x点不变, y可变可不变
                    not_half += min(nh, h);
                    // x点减半, y不变
                    half += nh;
                }
            }
            return {not_half, half};
        };
        auto [nh, h] = dfs2(0, -1);
        return min(nh, h);
    }
};

运行结果


之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

相关推荐
飞机和胖和黄几秒前
王道考研C语言第五周
c语言·考研·算法
fpcc8 分钟前
跟我学C++中级篇—线程局部存储的底层分析
c++
市场部需要一个软件开发岗位15 分钟前
一个无人机平台+算法监督平台的离线部署指南
java·python·算法·bash·无人机·持续部署
易知微EasyV数据可视化17 分钟前
数字孪生+AI:头部能源企业-监测光伏产品生命周期,驱动绿色智造零碳未来
人工智能·经验分享·能源·数字孪生
ygklwyf18 分钟前
零基础薄纱树套树——高级数据结构的结合
算法·线段树·树状数组·树套树
Cinema KI18 分钟前
C++11(中):可变参数模板将成为重中之重
开发语言·c++
GEO科技20 分钟前
氧气科技在AIIA签署《人工智能安全承诺:生成式引擎优化GEO 》
经验分享
凯子坚持 c20 分钟前
C++基于微服务脚手架的视频点播系统---客户端(2)
开发语言·c++·微服务
柯一梦22 分钟前
STL2--vector的介绍以及使用
开发语言·c++
txinyu的博客23 分钟前
解析muduo源码之 EPollPoller.h & EPollPoller.cc
c++