每日一题 2646. 最小化旅行的价格总和(困难,树)

在这里插入图片描述

  1. 分解为两个子问题,树中节点到节点的路径问题,价格减半树的最小值问题
  2. 由于它是无向的树,所以对于每一次旅行,以 start 为根,通过dfs寻找 end 就可以很简单地找到需要的路径且它是唯一的,这里我们统计每经过一个节点就令它的价格多加一份
  3. 通过第二步,我们得到了一棵全新的价格树,然后只要通过树形动态规划的方法,求得最小值即可
class Solution:
    def minimumTotalPrice(self, n: int, edges: List[List[int]], price: List[int], trips: List[List[int]]) -> int:
        ed = defaultdict(list)
        for edge in edges:
            ed[edge[0]].append(edge[1])
            ed[edge[1]].append(edge[0])

        pt = [0] * n

        def dfs(node, fa, to):
            if node == to:
                pt[node] += price[node]
                return True

            for ch in ed[node]:
                if ch == fa:
                    continue
                if dfs(ch, node, to):
                    pt[node] += price[node]
                    return True

            return False
        
        for trip in trips:
            dfs(trip[0], -1, trip[1])

        def cut(node, fa):
            docut = pt[node] // 2
            nocut = pt[node]
            for ch in ed[node]:
                if ch == fa:
                    continue
                a,b = cut(ch, node)
                docut += b
                nocut += min(a, b)
            return docut, nocut

        return min(cut(trips[0][0], -1))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

eyvr

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值