Data Structures & AlgorithmsVery hardProduct company OA
How many topological orders does this DAG on 6 vertices have? (counted by DP over bitmasks of already-placed vertices)
How many topological orders does this DAG on 6 vertices have? (counted by DP over bitmasks of already-placed vertices)
from functools import lru_cache
n = 6
edges = [(0, 2), (1, 2), (2, 3), (1, 4), (4, 5)]
pre = [0] * n
for a, b in edges: pre[b] |= 1 << a
@lru_cache(None)
def ways(mask):
if mask == (1 << n) - 1: return 1
return sum(ways(mask | 1 << v) for v in range(n)
if not mask >> v & 1 and pre[v] & mask == pre[v])
print(ways(0))- A. 12
- B. 20
- C. 16
- D. 24
Correct answer: C. 16
ways(mask) = Σ ways(mask ∪ {v}) over vertices v not yet placed whose prerequisites are all in mask – 2⁶ states instead of 6! permutations. Constraints: 0 and 1 precede 2, 2 precedes 3, and 1 precedes 4 which precedes 5. Merging the chain 0/1 → 2 → 3 with the branch 4 → 5 (which only needs 1 first) gives 16 orders. Counting only orders of 0, 1, 2, 3 (ignoring 4 and 5) or multiplying independent chains naively gives the wrong options.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Fenwick (binary indexed) tree, 1-based, built by point additions; then a[3] += 10. What is printed (the internal array, a range sum and a…
- Segment tree for range-minimum with lazy range-add (the pending add stays at a node and is applied on the way up instead of being pushed…
- Four cities, symmetric distances; the bitmask DP (Held–Karp) is compared with the nearest-neighbour heuristic, both starting and ending at…
- Maximum-weight independent set on a tree (no two chosen nodes adjacent) by tree DP returning (best if u taken, best if u skipped)…
- BFS that also counts the number of shortest paths. What is printed (dist[7], ways[7], ways[6], ways[4])? python from collections import…
- Dijkstra with a binary heap and lazy deletion (no decrease-key; outdated entries are skipped when popped). What is printed (dist to E…