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

运行结果


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

相关推荐
郝学胜-神的一滴几秒前
B站:从二次元到AI创新孵化器的华丽转身 | Google Cloud峰会见闻
开发语言·人工智能·算法
BHXDML几秒前
数据结构:(三)字符串——从暴力匹配到 KMP 的跨越
数据结构·算法
2301_790300965 分钟前
嵌入式GPU编程
开发语言·c++·算法
福赖10 分钟前
《堆 / 栈 / 静态区区别、内存泄漏原因及排查》
c++·内存··
迷途之人不知返13 分钟前
类和对象(2)
c++
半桔13 分钟前
【设计模式】策略模式:可插拔算法,从硬编码到灵活适配,体会“算法解耦“思想
java·c++·算法·设计模式·策略模式
sali-tec17 分钟前
C# 基于OpenCv的视觉工作流-章18-图像缩放
图像处理·人工智能·opencv·算法·计算机视觉
txinyu的博客26 分钟前
解析muduo源码之 BoundedBlockingQueue.h
c++
2401_8414956429 分钟前
【LeetCode刷题】LRU缓存
数据结构·python·算法·leetcode·缓存·lru缓存·查找
2401_8414956430 分钟前
【数据挖掘】Apriori算法
python·算法·数据挖掘·数据集·关联规则挖掘·关联规则·频繁项集挖掘