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 小时前
Leetcode 3432. Count Partitions with Even Sum Difference
算法·leetcode
wuhen_n3 小时前
LeetCode -- 15. 三数之和(中等)
前端·javascript·算法·leetcode
sin_hielo3 小时前
leetcode 2483
数据结构·算法·leetcode
无奈笑天下3 小时前
【麒麟镜像vmtools异常排查指导书】
linux·运维·经验分享·云计算·kylin
大数据追光猿3 小时前
【大数据Doris】生产环境,Doris主键模型全表7000万数据更新写入为什么那么慢?
大数据·经验分享·笔记·性能优化·doris
Xの哲學3 小时前
Linux多级时间轮:高精度定时器的艺术与科学
linux·服务器·网络·算法·边缘计算
大头流矢4 小时前
归并排序与计数排序详解
数据结构·算法·排序算法
阿闽ooo4 小时前
外观模式:从家庭电源控制看“简化接口“的设计智慧
c++·设计模式·外观模式
油泼辣子多加4 小时前
【信创】算法开发适配
人工智能·深度学习·算法·机器学习
不会学习?4 小时前
markdown笔记分享
经验分享·笔记