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

运行结果


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

相关推荐
TIF星空24 分钟前
【使用 C# 获取 USB 设备信息及进行通信】
开发语言·经验分享·笔记·学习·microsoft·c#
Smile丶凉轩2 小时前
Qt 界面优化(绘图)
开发语言·数据库·c++·qt
S01d13r4 小时前
LeetCode 解题思路 48(编辑距离、只出现一次的数字)
算法·leetcode·职场和发展
C_Liu_4 小时前
C语言:深入理解指针(5)
java·c语言·算法
small_wh1te_coder4 小时前
从经典力扣题发掘DFS与记忆化搜索的本质 -从矩阵最长递增路径入手 一步步探究dfs思维优化与编程深度思考
c语言·数据结构·c++·stm32·算法·leetcode·深度优先
枫景Maple4 小时前
LeetCode 45. 跳跃游戏 II(中等)
算法·leetcode
এ᭄画画的北北4 小时前
力扣-236.二叉树的最近公共祖先
算法·leetcode
z人间防沉迷k5 小时前
堆(Heap)
开发语言·数据结构·笔记·python·算法
不二狗6 小时前
每日算法 -【Swift 算法】Two Sum 问题:从暴力解法到最优解法的演进
开发语言·算法·swift
LabVIEW开发6 小时前
LabVIEW中样条插值实现及应用
算法·labview知识