Online store~30 min2s · 256 MBtarget O(n + log p) time, O(n) spacenumber-theory
You work on a warehouse system for an online shop. A shelf row has n bins, numbered 0 to n - 1, and each bin holds exactly one product. During a re-slotting, every product moves to a bin, and every bin ends up with exactly one product.
A product stays when it ends in the bin it started in. The floor team can only supervise a fixed number of unmoved products.
Your team lead asks: "In how many ways can the re-slotting be done so that exactly stay products stay in their own bin?" The row can have 100,000 bins, and the count can be very large.
Write count_reslots(n, stay).
n products over the n bins, one product in each bin.stay products end in their original bin. All the other products end in a different bin.1,000,000,007.n = 0 there is one empty re-slotting. Return 0 when no re-slotting fits.stay may be larger than n. Then no re-slotting fits.Input: n = 4, stay = 1
Output: 8Pick the one bin that stays: 4 choices. The other three products must all move, and 3 products can move with no one staying in 2 ways. Here are those 2 ways for each choice of the staying bin:
| Bin that stays | Ways to rearrange the other three with none staying |
|---|---|
| 0 | 2 |
| 1 | 2 |
| 2 | 2 |
| 3 | 2 |
The total is 4 × 2 = 8.
Input: n = 3, stay = 3
Output: 1Every product stays, which is one way.
Input: n = 3, stay = 2
Output: 0If two products stay, the third bin is the only one left for the third product. It must stay as well, so exactly 2 is impossible.
0 ≤ n ≤ 100,0000 ≤ stay ≤ 100,0001,000,000,007.Listing the rearrangements takes n! steps, and 12! is already 479,001,600. So the count must come from a formula. A formula over 100,000 values needs about 100,000 steps, and the numbers must be reduced modulo a prime as they grow.