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

运行结果


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

相关推荐
上海广测检测科技有限公司7 小时前
欧盟NIS2指令对中国制造商的供应链合规传导:判定边界与Article 21十条措施解读
经验分享
璞致电子7 小时前
基于 P201Pro 的 QPSK 无线收发|接收端基础知识 (2):从混乱星座到 QPSK 点簇,Costas‑Loop 载波同步 GNU Radio 实测
经验分享
朔北之忘 Clancy7 小时前
2025 CSP-J 第二轮真题解析
c++·青少年编程·题解·noip·csp·信奥赛·noi
longlongzihan7 小时前
LeetCode 17电话号码的字母组合:回溯算法(DFS)详解
c++·算法·leetcode·深度优先
yolo_guo7 小时前
调试mysql延迟与libevent回调实际发送回复时机问题
c++·mysql·libevent
封印师请假去地球钓鱼7 小时前
边解边变的问题:从“决策依赖“一词出发
人工智能·算法
今晚打老虎8 小时前
c++之提高A(前缀和)(第三课)
数据结构·c++·算法
不会就选b9 小时前
算法日常・每日刷题--<贪心>26
数据结构·算法
by209999 小时前
从结构体到对象:正式学习C++类的骨架、封装与this指针
c++·经验分享·学习
2601_9622186110 小时前
C语言中三种库的编译和使用方法
开发语言·c++