Count Subtrees With Max Distance Between Cities — LeetCode 1617 Python Solution
- Problem
- #1617
- Pattern
- Bit Manipulation
- Reading time
- 6 min
- Source
- leetcode.com
The problem
There are n cities numbered from 1 to n. You are given an array edges of size n-1, where edges[i] = [ui, vi] represents a bidirectional edge between cities ui and vi.
Example
- Input
- n = 4, edges = [[1,2],[2,3],[2,4]]
- Output
- [3,4,0]
- Explanation
- The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1.
Python solution
class Solution:
def countSubgraphsForEachDiameter(
self, n: int, edges: List[List[int]]
) -> List[int]:
def dfs(u: int, d: int = 0):
nonlocal mx, nxt, msk
if mx < d:
mx, nxt = d, u
msk ^= 1 << u
for v in g[u]:
if msk >> v & 1:
dfs(v, d + 1)
g = defaultdict(list)
for u, v in edges:
u, v = u - 1, v - 1
g[u].append(v)
g[v].append(u)
ans = [0] * (n - 1)
nxt = mx = 0
for mask in range(1, 1 << n):
if mask & (mask - 1) == 0:
continue
msk, mx = mask, 0
cur = msk.bit_length() - 1
dfs(cur)
if msk == 0:
msk, mx = mask, 0
dfs(nxt)
ans[mx - 1] += 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1617. Count Subtrees With Max Distance Between Cities is filed here because LeetCode tags it Bit Manipulation and Bitmask, which is the vocabulary this hub collects.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1617. Count Subtrees With Max Distance Between Cities?
- LeetCode 1617. Count Subtrees With Max Distance Between Cities is rated Hard on LeetCode.
- What topics does LeetCode 1617. Count Subtrees With Max Distance Between Cities cover?
- LeetCode 1617. Count Subtrees With Max Distance Between Cities is tagged Bit Manipulation, Tree, Dynamic Programming, Bitmask and Enumeration on LeetCode.