-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask_1443.py
More file actions
38 lines (28 loc) · 1.12 KB
/
task_1443.py
File metadata and controls
38 lines (28 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from typing import List
class Solution:
def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:
self.ans = 0
self.apples = n * [0]
def go(u, par):
if hasApple[u]:
self.apples[u] = 1
for v in gr[u]:
if v != par:
self.apples[u] += go(v, u)
return self.apples[u]
def dfs(u, par):
if not self.apples[u]:
return
for v in gr[u]:
if self.apples[v] and v != par:
self.ans += 1
dfs(v, u)
gr = [[] for x in range(n)]
for x, y in edges:
gr[x].append(y)
gr[y].append(x)
go(0, -1)
dfs(0, -1)
return 2 * self.ans
print(Solution().minTime(n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [False,False,True,False,True,True,False]))
print(Solution().minTime(n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [False,False,True,False,False,True,False]))