Skip to content

Commit 289e161

Browse files
authored
Create Maximize the Number of Target Nodes After Connecting Trees I.py
1 parent e4f09f4 commit 289e161

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
'''
2+
There exist two undirected trees with n and m nodes, with distinct labels in ranges [0, n - 1] and [0, m - 1], respectively.
3+
4+
You are given two 2D integer arrays edges1 and edges2 of lengths n - 1 and m - 1, respectively, where edges1[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the first tree and edges2[i] = [ui, vi] indicates that there is an edge between nodes ui and vi in the second tree. You are also given an integer k.
5+
6+
Node u is target to node v if the number of edges on the path from u to v is less than or equal to k. Note that a node is always target to itself.
7+
8+
Return an array of n integers answer, where answer[i] is the maximum possible number of nodes target to node i of the first tree if you have to connect one node from the first tree to another node in the second tree.
9+
10+
Note that queries are independent from each other. That is, for every query you will remove the added edge before proceeding to the next query.
11+
'''
12+
13+
from collections import deque
14+
from typing import List
15+
16+
class Solution:
17+
def maxTargetNodes(self, edges1: List[List[int]], edges2: List[List[int]], k: int) -> List[int]:
18+
def build_graph(edges):
19+
n = len(edges) + 1
20+
graph = [[] for _ in range(n)]
21+
for u, v in edges:
22+
graph[u].append(v)
23+
graph[v].append(u)
24+
return graph
25+
26+
def bfs_count_max(graph, max_dist):
27+
n = len(graph)
28+
result = [0] * n
29+
for start in range(n):
30+
visited = [False] * n
31+
q = deque()
32+
q.append((start, 0))
33+
visited[start] = True
34+
count = 1
35+
while q:
36+
node, dist = q.popleft()
37+
if dist == max_dist:
38+
continue
39+
for neighbor in graph[node]:
40+
if not visited[neighbor]:
41+
visited[neighbor] = True
42+
q.append((neighbor, dist + 1))
43+
count += 1
44+
result[start] = count
45+
return result
46+
47+
g1 = build_graph(edges1)
48+
g2 = build_graph(edges2)
49+
50+
if k == 0:
51+
return [1] * len(g1)
52+
53+
cnt1 = bfs_count_max(g1, k)
54+
cnt2 = bfs_count_max(g2, k - 1)
55+
max_cnt2 = max(cnt2)
56+
57+
return [cnt + max_cnt2 for cnt in cnt1]

0 commit comments

Comments
 (0)