Skip to content

Commit 833a304

Browse files
authored
Create maximize-the-number-of-target-nodes-after-connecting-trees-ii.py
1 parent 872509b commit 833a304

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Time: O(n + m)
2+
# Space: O(n + m)
3+
4+
# bfs
5+
class Solution(object):
6+
def maxTargetNodes(self, edges1, edges2):
7+
"""
8+
:type edges1: List[List[int]]
9+
:type edges2: List[List[int]]
10+
:rtype: List[int]
11+
"""
12+
def bfs(adj):
13+
result = [0]*len(adj)
14+
parity = 0
15+
lookup = [-1]*len(adj)
16+
lookup[0] = parity
17+
q = [0]
18+
while q:
19+
new_q = []
20+
for u in q:
21+
for v in adj[u]:
22+
if lookup[v] != -1:
23+
continue
24+
lookup[v] = parity^1
25+
new_q.append(v)
26+
q = new_q
27+
parity ^= 1
28+
cnt = sum(lookup)
29+
return [cnt if lookup[u] else len(adj)-cnt for u in xrange(len(adj))]
30+
31+
def find_adj(edges):
32+
adj = [[] for _ in xrange(len(edges)+1)]
33+
for u, v in edges:
34+
adj[u].append(v)
35+
adj[v].append(u)
36+
return adj
37+
38+
adj2 = find_adj(edges2)
39+
mx = max(bfs(adj2))
40+
adj1 = find_adj(edges1)
41+
return [mx+x for x in bfs(adj1)]

0 commit comments

Comments
 (0)