Engineering platform~40 min4s · 256 MBtarget O(2^n × n) time, O(2^n) spacebit-manipulation · dp
You work on a build platform. A release has n steps, such as compile, test, package and sign. Some steps must run before others, and the platform runs one step at a time.
The release manager wants to know how many different orders are valid. An order is valid when every step comes after all the steps it needs. Your team lead asks: "How many valid orders are there?" A release has at most 18 steps, and the answer can be large.
Write count_build_orders(n, needs).
0 to n - 1.needs[i] = [a, b] means step a must run before step b. Needs may repeat, and they may form a cycle.n steps in which every need is met.Input: n = 4, needs = [[0, 1], [0, 2], [1, 3], [2, 3]]
Output: 2Step 0 must run first, and step 3 must run last. Steps 1 and 2 can run in either order, so the valid orders are 0, 1, 2, 3 and 0, 2, 1, 3.
| Steps run so far | Orders that reach this state |
|---|---|
| none | 1 |
| 0 | 1 |
| 0, 1 | 1 |
| 0, 2 | 1 |
| 0, 1, 2 | 2 |
| 0, 1, 2, 3 | 2 |
Input: n = 3, needs = []
Output: 6Three free steps can run in any of 3! = 6 orders.
Input: n = 3, needs = [[0, 1], [1, 2], [2, 0]]
Output: 0The steps wait for each other in a circle, so no order works.
1 ≤ n ≤ 180 ≤ len(needs) ≤ 400[a, b], 0 ≤ a, b < n.There are 18! = 6.4 × 10^15 orders, which is too many to try. But there are only 2^18 = 262,144 sets of steps. A method that works on sets needs about 2^18 × 18 = 4.7 million steps, which is fast. The count can exceed 32 bits, which is why the answer is taken modulo a prime.