Problem 597268 · hard · Phase 05 Advanced Algorithms & Graphs

Count the Valid Orderings

topological sort · bitmask dp · counting

You are given n tasks numbered 0 .. n-1 and a list edges where [a, b] means task a must be performed before task b. Return the number of distinct orders in which all n tasks can be performed while respecting every constraint. If the constraints are contradictory (contain a cycle), return 0.

Examples

Input:  n = 3, edges = []
Output: 6

Input:  n = 3, edges = [[0, 1], [0, 2]]
Output: 2
Explanation: 0 must come first; 1 and 2 may follow in either order.

Input:  n = 2, edges = [[0, 1], [1, 0]]
Output: 0

Constraints

  • 1 <= n <= 14, 0 <= len(edges) <= n * (n - 1)
  • The answer fits in a Python int (up to 14! = 87178291200).
  • Target: O(2**n * n) time.

Goals

  • Represent 'the set of tasks already done' as a bitmask
  • Count linear extensions of a small partial order with subset DP
Starting Python…