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

运行结果


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

相关推荐
IronMurphy5 小时前
【算法四十三】279. 完全平方数
算法
墨染天姬5 小时前
【AI】Hermes的GEPA算法
人工智能·算法
papership6 小时前
【入门级-数据结构-3、特殊树:完全二叉树的数组表示法】
数据结构·算法·链表
smj2302_796826526 小时前
解决leetcode第3911题.移除子数组元素后第k小偶数
数据结构·python·算法·leetcode
Beginner x_u7 小时前
链表专题:JS 实现原理与高频算法题总结
javascript·算法·链表
c++之路8 小时前
C++信号处理
开发语言·c++·信号处理
德思特9 小时前
德思特新品 | 双小区5G NR基站模拟器正式推出,支持从单点验证迈向网络级测试
经验分享·无线通信·射频微波
_深海凉_10 小时前
LeetCode热题100-寻找两个正序数组的中位数
算法·leetcode·职场和发展
故事还在继续吗10 小时前
C++20关键特性
开发语言·c++·c++20
suuijbd10 小时前
某小厂Java开发面经
经验分享