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

运行结果


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

相关推荐
圣保罗的大教堂2 分钟前
leetcode 2799. 统计完全子数组的数目 中等
leetcode
SsummerC9 分钟前
【leetcode100】组合总和Ⅳ
数据结构·python·算法·leetcode·动态规划
YuCaiH37 分钟前
数组理论基础
笔记·leetcode·c·数组
2301_807611491 小时前
77. 组合
c++·算法·leetcode·深度优先·回溯
微网兔子2 小时前
伺服器用什么语言开发呢?做什么用什么?
服务器·c++·后端·游戏
YuforiaCode2 小时前
第十三届蓝桥杯 2022 C/C++组 修剪灌木
c语言·c++·蓝桥杯
YOULANSHENGMENG2 小时前
linux 下python 调用c++的动态库的方法
c++·python
CodeWithMe2 小时前
【C++】STL之deque
开发语言·c++
SsummerC2 小时前
【leetcode100】零钱兑换Ⅱ
数据结构·python·算法·leetcode·动态规划
炯哈哈3 小时前
【上位机——MFC】运行时类信息机制
开发语言·c++·mfc·上位机