Chat app~40 min2s · 256 MBtarget O((n + e) log n) time, O(n + e) spaceclassic twin: lc-1203topological-sort
A messaging platform runs n processing stages, numbered from 0. Some stages belong to a worker pool, numbered from 0 to m - 1. A pool must run all its stages in one unbroken session, because starting a pool is slow.
A stage with no pool runs alone, as a pool of one. Rules say that one stage must run before another, and they apply to stages of the same pool and of different pools.
Write build_order(n, m, pool, before).
pool[i] is the pool of stage i, or -1 when it has none. Some pools may have no stage.before[j] is [a, b]: stage a must run before stage b.m + i, where i is its stage number. Among the pools that are ready, run the smallest pool number first. Inside a pool, run the smallest ready stage first.Input: n = 8, m = 2, pool = [-1,0,0,1,1,0,1,-1], before = [[6,1],[5,2],[6,3],[3,4],[6,4]]
Output: [6, 3, 4, 1, 5, 2, 0, 7]Pool 0 holds stages 1, 2 and 5. Pool 1 holds 3, 4 and 6. Stages 0 and 7 are pools of one, numbered m + i, which is 2 and 9.
The rule [6,1] crosses pools, so pool 1 must run before pool 0. The other rules stay inside a pool.
| Step | Pool run | Ready pools before | Stages in order |
|---|---|---|---|
| 1 | 1 | 1, 2, 9 | 6, then 3, then 4 |
| 2 | 0 | 0, 2, 9 | 1 and 5 are ready; 1 goes first; then 5, then 2 |
| 3 | 2 | 2, 9 | 0 |
| 4 | 9 | 9 | 7 |
The order is 6, 3, 4, 1, 5, 2, 0, 7.
Input: n = 4, m = 2, pool = [0,1,0,1], before = [[0,1],[3,2]]
Output: []Stage 0, in pool 0, must run before stage 1, in pool 1. Stage 3, in pool 1, must run before stage 2, in pool 0. Each pool would have to run first, so no order exists.
Input: n = 3, m = 0, pool = [-1,-1,-1], before = [[2,0]]
Output: [1, 2, 0]Every stage is a pool of one, numbered 0, 1 and 2. Stage 2 must come before stage 0, so pools 1 and 2 are ready first, and 1 is smaller.
1 ≤ n ≤ 30,000, 0 ≤ m ≤ n, and pool has n entries from -1 to m - 10 ≤ before.length ≤ 100,000, and each rule joins two different stages from 0 to n - 1Placing one pool at a time, and scanning every rule to find the next ready pool, costs about n × e = 30,000 × 100,000 = 3 × 10^9 steps. Two heaps, one for pools and one inside each pool, give each pick in O(log n). The whole run costs O((n + e) log n), about 2 × 10^6 steps.