If person moves to a different seat , the color rule gives . Together with the distance limit, this means the only possible seats are , , and , excluding any that do not exist.
Every valid arrangement can be divided from left to right into blocks of length , where one person stays, and blocks of length , where three consecutive people rotate. A block of length starting at person has the following movements.
The people occupying these three seats are therefore from left to right. Rotation in the opposite direction is not allowed.
Let be the number of ways to fill the first seats using the first people. Set and initialize the remaining values to . For each from through , add the following two possibilities.
Perform every addition modulo . The answer is . Both the time complexity and the space complexity are .
Proof
Suppose an initial segment of people has been assigned exactly to the seats in the same initial segment. Let be the smallest remaining person and seat number.
If person stays in seat , they form a block of length . Remove this person and seat and apply the same reasoning to the remainder.
If person moves, seat has already been assigned or does not exist, so they must move to seat . The only people who could occupy the now-empty seat are , , and . Person has already been assigned or does not exist, while person has moved elsewhere. Thus, person must occupy seat .
Solution written by GPT6
FOf the seats available to person , seat has already been assigned or does not exist, and seat is occupied by person . Therefore, person must move to seat . If any required person or seat does not exist, this case is impossible. Otherwise, these three consecutive people and seats form a complete block.
Repeating this argument gives a unique decomposition of every valid arrangement into blocks of length or . Conversely, arranging each block as described uses every person and seat exactly once and satisfies the color and distance rules. A block of length is allowed exactly when that person's condition is not M. A block of length is allowed exactly when none of its three conditions is F.
The final block has length or , and these cases are disjoint. For each valid arrangement of the preceding segment, there is exactly one way to append the chosen final block. Hence, the recurrence counts every valid arrangement exactly once.