One-Dimensional Cellular Automaton

Time limit2sMemory limit128 MB

Summary
Simulate a linear recurrence over N cells modulo M for up to 1e9 steps using fast matrix exponentiation.
Level

Medium6 of 10

Topics
Matrix, Math, Simulation
Solved
No attempts yet

Problem

There is a one-dimensional cellular automaton made of NN cells, numbered from 00 to N−1N-1.

Each cell has a state, a non-negative integer less than MM. The states evolve as time advances by one unit. Let S(i,t)S(i, t) be the state of cell ii at time tt. The state at time t+1t+1 is given by

S(i,t+1)=(A×S(i−1,t)+B×S(i,t)+C×S(i+1,t)) mod MS(i, t+1) = (A \times S(i-1, t) + B \times S(i, t) + C \times S(i+1, t)) \bmod M

where AA, BB, CC are non-negative integers. For i<0i < 0 or i≥Ni \ge N, we take S(i,t)=0S(i, t) = 0.

Given the initial state of the automaton, write a program that computes the state of the cells after TT time units.

Input

Each test case has the following format.

N M A B C T
S(0,0) S(1,0) ... S(N-1,0)

The constraints are 0<N≤500 < N \le 50, 0<M≤10000 < M \le 1000, 0≤A,B,C<M0 \le A, B, C < M, and 0≤T≤1090 \le T \le 10^9.

The last line of the input contains six zeros.

Output

For each test case, output the state of the cells at time TT, in the following format.

S(0,T) S(1,T) ... S(N-1,T)

Each cell state is an integer, and the values are separated by spaces.

Examples3

  1. Example 1

    Input
    5 4 1 3 2 0
    0 1 2 0 1
    5 7 1 3 2 1
    0 1 2 0 1
    5 13 1 3 2 11
    0 1 2 0 1
    5 5 2 0 1 100
    0 1 2 0 1
    6 6 0 2 3 1000
    0 1 2 0 1 4
    20 1000 0 2 3 1000000000
    0 1 2 0 1 0 1 2 0 1 0 1 2 0 1 0 1 2 0 1
    30 2 1 0 1 1000000000
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0
    30 2 1 1 1 1000000000
    1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    30 5 2 3 1 1000000000
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0
    
    Expected output
    0 1 2 0 1
    2 0 0 4 3
    2 12 10 9 11
    3 0 4 2 1
    0 4 2 0 4 4
    0 376 752 0 376 0 376 752 0 376 0 376 752 0 376 0 376 752 0 376
    1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
    1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0
    1 1 3 2 2 2 3 3 1 4 3 1 2 3 0 4 3 3 0 4 2 2 2 2 1 1 2 1 3 0
    
  2. Example 2

    Input
    1 5 0 3 0 4
    2
    0 0 0 0 0 0
    
    Expected output
    2
    
  3. Example 3

    Input
    4 10 5 5 5 0
    3 7 1 9
    0 0 0 0 0 0
    
    Expected output
    3 7 1 9