-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathminimum-increments-to-equalize-leaf-paths.py
More file actions
76 lines (71 loc) · 1.98 KB
/
minimum-increments-to-equalize-leaf-paths.py
File metadata and controls
76 lines (71 loc) · 1.98 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# Time: O(n)
# Space: O(n)
# iterative dfs
class Solution(object):
def minIncrease(self, n, edges, cost):
"""
:type n: int
:type edges: List[List[int]]
:type cost: List[int]
:rtype: int
"""
def iter_dfs():
result = n-1
mx = [0]*len(adj)
stk = [(1, (0, -1))]
while stk:
step, (u, p) = stk.pop()
if step == 1:
stk.append((2, (u, p)))
for v in reversed(adj[u]):
if v != p:
stk.append((1, (v, u)))
elif step == 2:
cnt = 0
for v in adj[u]:
if v == p or mx[v] < mx[u]:
continue
if mx[v] > mx[u]:
mx[u] = mx[v]
cnt = 0
cnt += 1
result -= cnt
mx[u] += cost[u]
return result
adj = [[] for _ in xrange(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
return iter_dfs()
# Time: O(n)
# Space: O(n)
# dfs
class Solution2(object):
def minIncrease(self, n, edges, cost):
"""
:type n: int
:type edges: List[List[int]]
:type cost: List[int]
:rtype: int
"""
def dfs(u, p):
mx = cnt = 0
for v in adj[u]:
if v == p:
continue
c = dfs(v, u)
if c < mx:
continue
if c > mx:
mx = c
cnt = 0
cnt += 1
result[0] -= cnt
return mx+cost[u]
adj = [[] for _ in xrange(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
result = [n-1]
dfs(0, -1)
return result[0]