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

运行结果


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

相关推荐
urkay-20 分钟前
Android 图片轮廓提取与重叠轮廓合并处理
android·算法·iphone
七七肆十九20 分钟前
PTA 7-38 数列求和-加强版
数据结构·算法
SWAGGY..22 分钟前
【C++初阶】:(5)内存管理
java·c++·算法
Zarek枫煜36 分钟前
zig与C3的算法 -- 桶排序
c语言·嵌入式硬件·算法
Rooting++1 小时前
C语言中的共用体应用场景
算法
liulilittle1 小时前
SQLite3增删改查(C
c语言·开发语言·数据库·c++·sqlite
CVer儿1 小时前
c++的移动语义
c++
We་ct1 小时前
LeetCode 4. 寻找两个正序数组的中位数:二分优化思路详解
前端·数据结构·算法·leetcode·typescript·二分
逻辑君2 小时前
Research in Brain-inspired Computing [7]-带关节小人(3个)推箱的类意识报告
c++·人工智能·神经网络·机器学习
仍然.2 小时前
算法题目---位运算
算法