forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
create-components-with-same-value.py
112 lines (104 loc) · 3.22 KB
/
create-components-with-same-value.py
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# Time: O(n * sqrt(n))
# Space: O(n)
# bfs, greedy
class Solution(object):
def componentValue(self, nums, edges):
"""
:type nums: List[int]
:type edges: List[List[int]]
:rtype: int
"""
def bfs(target):
total = nums[:]
lookup = [len(adj[u]) for u in xrange(len(adj))]
q = [u for u in xrange(len(adj)) if lookup[u] == 1]
while q:
new_q = []
for u in q:
if total[u] > target:
return False
if total[u] == target:
total[u] = 0
for v in adj[u]:
total[v] += total[u]
lookup[v] -= 1
if lookup[v] == 1:
new_q.append(v)
q = new_q
return True
result = 0
adj = [[] for _ in xrange(len(nums))]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
total = sum(nums)
for cnt in reversed(xrange(2, len(nums)+1)):
if total%cnt == 0 and bfs(total//cnt):
return cnt-1
return 0
# Time: O(n * sqrt(n))
# Space: O(n)
# iterative dfs, greedy
class Solution2(object):
def componentValue(self, nums, edges):
"""
:type nums: List[int]
:type edges: List[List[int]]
:rtype: int
"""
def iter_dfs(target):
total = nums[:]
stk = [(1, (0, -1))]
while stk:
step, (u, p) = stk.pop()
if step == 1:
stk.append((2, (u, p)))
for v in adj[u]:
if v == p:
continue
stk.append((1, (v, u)))
elif step == 2:
for v in adj[u]:
if v == p:
continue
total[u] += total[v]
if total[u] == target:
total[u] = 0
return total[0]
result = 0
adj = [[] for _ in xrange(len(nums))]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
total = sum(nums)
for cnt in reversed(xrange(2, len(nums)+1)):
if total%cnt == 0 and iter_dfs(total//cnt) == 0:
return cnt-1
return 0
# Time: O(n * sqrt(n))
# Space: O(n)
# dfs, greedy
class Solution3(object):
def componentValue(self, nums, edges):
"""
:type nums: List[int]
:type edges: List[List[int]]
:rtype: int
"""
def dfs(u, p, target):
total = nums[u]
for v in adj[u]:
if v == p:
continue
total += dfs(v, u, target)
return total if total != target else 0
result = 0
adj = [[] for _ in xrange(len(nums))]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
total = sum(nums)
for cnt in reversed(xrange(2, len(nums)+1)):
if total%cnt == 0 and dfs(0, -1, total//cnt) == 0:
return cnt-1
return 0