AOJ1327 One-Dimensional Cellular Automaton

One-Dimensional Cellular Automaton

There is a one-dimensional cellular automaton consisting of cells. Cells are numbered from 0 to N − 1. Each cell has a state represented as a non-negative integer less than M. The states of cells evolve through discrete time steps. We denote the state of the i-th cell at time t as S( i, t).

をそのままやると となり間に合わない.変換行列を

とする.これの行列のの係数となる.よって

この変換行列の 乗は で出来るので となり間に合う.
行列累乗の問題を初めて解けた(文字のまま展開していたら気付いた).非常に嬉しい.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <algorithm>
#include <sstream>
#include <map>
#include <set>

#define REP(i,k,n) for(int i=k;i<n;i++)
#define rep(i,n) for(int i=0;i<n;i++)
#define INF 1<<30
#define pb push_back
#define mp make_pair

using namespace std;
typedef long long ll;
typedef pair<int,int> P;

int MOD;

struct Mat {
  vector<vector<ll> > dat;
  int n;

  Mat(int n) : n(n), dat(n, vector<ll>(n)) {}

  Mat(vector<vector<ll> > dat) : n(dat.size()), dat(dat) {}

  Mat I(int n) {
      Mat ret(n);
      rep(i, n) ret.dat[i][i] = 1;
      return ret;
  }

  Mat mul(Mat &b) {
        Mat ret(n);
      rep(i, n) rep(j, n) rep(k, n) (ret.dat[i][j] += dat[i][k] * b.dat[k][j]) %= MOD;
        return ret;
  }

  Mat pow(ll b) {
      Mat ret = I(n);
        for (Mat A = *this; b > 0; A = A.mul(A) , b /= 2) if (b & 1) ret = A.mul(ret);
        return ret;
  }
};

int main() {
  int n, m, a, b, c, t;
  while(cin >> n >> m >> a >> b >> c >> t) {
      if(n == 0 && m == 0 && a == 0 && b == 0 && c == 0 && t == 0) break;

      MOD = m;

      vector<int> s(n);
      rep(i, n) cin >> s[i];

      int s1 = -1, s2 = 0, s3 = 1;
      Mat mat(n);
      rep(i, n) {
          if(s1 >= 0) {
              mat.dat[i][s1] = a;
          }
          mat.dat[i][s2] = b;
          if(s3 < n) {
              mat.dat[i][s3] = c;
          }
          
          s1++; s2++; s3++;
      }

      Mat ret = mat.pow(t);

      rep(i, n) {
          ll sum = 0;
          rep(j, n) {
              sum += s[j] * ret.dat[i][j];
              sum %= MOD;
          }

          cout << sum;

          if(i == n-1) cout << endl;
          else cout << " ";
      }
  }

  return 0;
}
Mar 24th, 2016