Online store~25 min2s · 256 MBtarget O((n + m) log n) time, O(n + m) spacetopological-sort · heaps
A seller app shows a setup checklist to new sellers. Some steps need other steps first: you cannot connect payments before you add a business name. The app shows the checklist in rounds, and a seller can finish only a few steps in one round.
In each round, the app offers the steps whose prerequisites were all finished in earlier rounds. If more than cap steps are ready, it offers the ones with the smallest numbers. You want the round in which each step is offered.
Write setup_rounds(n, needs, cap).
0 to n - 1.needs[i] = [a, b] means that step a needs step b to be finished first. Rows can repeat.cap of the ready steps, smallest numbers first. A step is ready when every prerequisite was taken in an earlier round. Steps taken in this round do not make other steps ready in the same round.Input: n = 7, needs = [[1, 0], [2, 0], [3, 0], [4, 1], [4, 2], [5, 4], [6, 6]], cap = 2
Output: [1, 2, 2, 3, 3, 4, -1]The table lists the ready steps and what each round takes.
| Round | Ready steps (smallest first) | Taken (cap 2) | Released afterwards |
|---|---|---|---|
| 1 | 0 | 0 | 1, 2, 3 |
| 2 | 1, 2, 3 | 1, 2 | 4 (needs 1 and 2) |
| 3 | 3, 4 | 3, 4 | 5 |
| 4 | 5 | 5 | none |
Steps 1, 2 and 3 need step 0, and step 4 needs steps 1 and 2. Step 5 needs step 4. Step 6 needs itself, so it never becomes ready.
With cap = 2, step 3 has to wait for round 3. The table shows the rounds.
Input: n = 3, needs = [[1, 0], [2, 0]], cap = 1
Output: [1, 2, 3]With a cap of one, steps 1 and 2 are ready after round 1, and step 1 goes first.
Input: n = 2, needs = [[0, 1], [1, 0]], cap = 5
Output: [-1, -1]Each step needs the other, so neither step is ever ready.
1 ≤ n ≤ 100,000 (steps)0 ≤ needs.length ≤ 200,000, each row [a, b] with 0 ≤ a, b < n1 ≤ cap ≤ 100,000Scanning every step and every prerequisite in every round costs about rounds × (n + m) steps. The rounds can number n, so that is up to about 3 × 10^10 steps. Counting unmet prerequisites per step turns "all prerequisites done" into a check against 0, and a min-heap of ready steps gives the smallest ready number at once. Each step enters and leaves the heap once.