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

运行结果


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

相关推荐
wen__xvn2 分钟前
基础算法集训第17天:二分查找
算法·leetcode·职场和发展
myloveasuka3 分钟前
MREQ̅ 信号
笔记·算法·计算机组成原理
耶耶耶耶耶~4 分钟前
关于软件开发的一些思考
c++
量子炒饭大师6 分钟前
【C++入门】Cyber骇客构造器的核心六元组 —— 【类的默认成员函数】明明没写构造函数也能跑?保姆级带你掌握六大类的默认成员函数(上:函数篇)
开发语言·c++·dubbo·默认成员函数
亲爱的非洲野猪6 分钟前
动态规划进阶:区间DP深度解析
算法·动态规划
学工科的皮皮志^_^8 分钟前
以太网PHY芯片学习RTF8211
经验分享·嵌入式硬件·学习·以太网·phy
QiZhang | UESTC12 分钟前
【算法题学习方法调整】回溯核心逻辑调整:从记代码到套逻辑调整
算法·学习方法
救救孩子把14 分钟前
59-机器学习与大模型开发数学教程-5-6 Adam、RMSProp、AdaGrad 等自适应优化算法
人工智能·算法·机器学习
Σίσυφος190014 分钟前
PCL 中常用的滤波对比
算法
进击的小头14 分钟前
连续系统离散化方法(嵌入式信号处理实战指南)
c语言·算法·信号处理