Stacking Cups
Time limit2sMemory limit1024 MB
Count the valid stacks of exactly N red and blue cups, where each cup on top sits on two neighbors with at least one red, modulo prime P.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Combinatorics
- Solved
- No attempts yet
Problem
Sports stacking is a sport in which cups are stacked quickly in various ways. Hanna, the president of the sports stacking association, wants to boost sales of a newly released red cup by introducing a new sports stacking event. (In the figure, the red cups are the ones with horizontal stripes.) The rules are as follows.
Each participant prepares red cups and blue cups. From these, the participant must build any arrangement that follows the rules using cups. The rules for stacking cups are as follows.
- The bottom layer must consist of cups placed in one continuous row.
- A cup can be placed above the center of two adjacent cups. This can be repeated to build several layers.
- To place a cup on top of two adjacent cups, at least one of those two cups must be red.

Cups of the same color cannot be told apart. Find the number of ways to stack the cups, modulo the given prime . Two arrangements that are mirror images of each other are counted as different.
Input
The first line contains the integer , the number of cups to stack, and the prime to divide by, separated by a space.
Output
Print the number of ways to stack cups that satisfy the rules, modulo .
Constraints
- is prime.
Hint
There are ways to stack cups, as shown in the following figure.
