[leetcode] 1443. Minimum Time to Collect All Apples in a Tree

网友投稿 272 2022-08-25

[leetcode] 1443. Minimum Time to Collect All Apples in a Tree

Description

Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend in order to collect all apples in the tree starting at vertex 0 and coming back to this vertex.

The edges of the undirected tree are given in the array edges, where edges[i] = [fromi, toi] means that exists an edge connecting the vertices fromi and toi. Additionally, there is a boolean array hasApple, where hasApple[i] = true means that vertex i has an apple, otherwise, it does not have any apple.

Example 1:

Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]Output: 8 Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.

Example 2:

Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false]Output: 6Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.

Example 3:

Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]Output: 0

Constraints:

1 <= n <= 10^5edges.length == n-1edges[i].length == 20 <= fromi, toi <= n-1fromi < toihasApple.length == n

分析

题目的意思是:给你定一颗二叉树,求出遍历所有苹果的最小时间。这道题的二叉树是用边的形式给出来的,挺新颖的,当然我也没做出来。大概思路是要建立一个无向图,进行深度优先搜索,然后记录代价并求和就行了。注意无向图是有环的,不要陷入环里面去了,所以要比较一下当前结点的parent是否等于child。下面的代码中如果遍历的是非根结点

hasApple[parent] = True

主要是递归计算回传的时候记录中间经过的边,可以说是一个小trick了,我也想不到哈哈哈。

代码

class Solution: def solve(self,routes,hasApple,idx,parent): cost=0 for child in routes[idx]: if(child!=parent): cost+=self.solve(routes,hasApple,child,idx) if(idx!=0 and hasApple[idx]): hasApple[parent]=True return cost+2 return cost def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int: routes=collections.defaultdict(list) res=0 for k,v in edges: routes[k].append(v) routes[v].append(k) res=self.solve(routes,hasApple,0,0) return res

参考文献

​​[LeetCode] [Python] Beats 100% Short DFS Easy to Read​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:[leetcode] 23. 合并K个升序链表
下一篇:从理想营销看理想one这款车!(理想one汽车销售店)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~