Crate stacks
HardOnline Assessment
Count the legal ways to stack crates of several types, modulo 1,000,000,007.
A loading dock builds a stack of exactly n crates, listed from the bottom crate to the top crate. There are k crate types numbered 0 to k - 1, and any type can be used any number of times. A stack is legal when it obeys both rules:
- Run limit. At most
limits[t]crates of typetmay sit directly on top of each other in a row. A row of more than that many consecutive crates of typetis not allowed. - Banned pairs.
bannedis a list of pairs[a, b]witha != b. For such a pair, a crate of typebmay not sit directly on top of a crate of typea. The pair is directional:[a, b]being banned says nothing about a crate of typeasitting on a crate of typeb.
Two stacks are different if they differ in the type of the crate at any position.
Input: n, an integer; limits, a list of k integers (so k is len(limits)); and banned, a list of [a, b] pairs.
Output: an integer, the number of legal stacks of height n, modulo 1_000_000_007. If no stack is legal, return 0.
The stack height can be astronomically large, so building the stack one crate at a time will be too slow.
Example 1
- Input:
- [3,[1,1],[]]
- Output:
- 2
- Explanation
- Both types allow only one crate in a row, so the types must alternate. The legal stacks are
0,1,0and1,0,1, so the answer is 2.
Example 2
- Input:
- [3,[2,2],[[1,0]]]
- Output:
- 2
- Explanation
- The pair
[1, 0]says a type 0 crate may not sit directly on a type 1 crate. So once a type 1 crate appears, every crate above it is also type 1. With a run limit of 2 for each type and height 3, the only legal stacks are0,1,1and0,0,1, so the answer is 2.
Example 3
- Input:
- [5,[3,1],[]]
- Output:
- 10
- Explanation
- Write type 0 as A (at most three in a row) and type 1 as B (never two in a row). The 10 legal stacks of height 5 are AAABA, AABAA, AABAB, ABAAA, ABAAB, ABABA, BAAAB, BAABA, BABAA and BABAB.
Constraints
1 <= n <= 1,000,000,000,000,000(1015)1 <= k <= 4,1 <= limits[t] <= 30 <= banned.length <= 12, every pair has0 <= a, b < kanda != b