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);
    }
};

运行结果


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

相关推荐
三月微暖寻春笋1 分钟前
【和春笋一起学C++】(五十)在构造函数中使用new时的注意事项
c++·new·构造函数
Hello eveybody2 分钟前
冒泡、选择、插入排序简介(C++)
数据结构·算法·排序算法
CoderYanger4 分钟前
贪心算法:2.将数组和减半的最少操作次数
java·算法·leetcode·贪心算法·1024程序员节
Chen--Xing6 分钟前
LeetCode 49.字母异位词分组
c++·python·算法·leetcode·rust
长安er10 分钟前
LeetCode 235 & 236 最近公共祖先(LCA)解题总结
算法·leetcode·二叉树·递归·lca
im_AMBER13 分钟前
Leetcode 77 数组中的最大数对和 | 统计坏数对的数目
笔记·学习·算法·leetcode
代码游侠18 分钟前
学习笔记——Linux 进程管理笔记
linux·运维·笔记·学习·算法
lxmyzzs19 分钟前
【图像算法 - 38】工业巡检应用:基于 YOLO 与 OpenCV 的高精度管道缺陷检测系统实现
opencv·算法·yolo·管道检测
老鱼说AI20 分钟前
算法基础教学:哈希表
数据结构·算法·散列表
lxmyzzs22 分钟前
【图像算法 - 39】环保监测应用:基于 YOLO 与 OpenCV 的高精度水面垃圾检测系统实现
opencv·算法·yolo·水下垃圾检测