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#上位机6 分钟前
halcon图像去噪—均值滤波
图像处理·算法·均值算法·halcon
TRSsd12 分钟前
如何将文件制作成二维码?用于讲解旅游纪念品?
经验分享
曾几何时`21 分钟前
347. 前 K 个高频元素 分别使用sort和priority_queue 对哈希结构自定义排序
算法
AA陈超23 分钟前
LyraRPG:001.创建RPGCore插件
c++·笔记·学习·ue5·虚幻引擎·lyra
无限进步_25 分钟前
C++从入门到类和对象完全指南
开发语言·c++·windows·git·后端·github·visual studio
小李小李快乐不已28 分钟前
图论理论基础(3)
数据结构·c++·算法·图论
牙牙要健康28 分钟前
【open3d】示例:自动计算点人脸点云模型面部朝向算法
人工智能·python·算法
youngee1130 分钟前
hot100-41二叉搜索树中第K小的元素
算法
星竹晨L43 分钟前
C++红黑树:理论与实践相结合的平衡艺术
开发语言·数据结构·c++
汇能感知44 分钟前
摄像头模块在厨电领域的深度应用
经验分享·笔记·科技