Question: Click to open the link
A cellular automation contains N grids. The value of each lattice is the value of all grids whose distance is not greater than D. The final result is obtained.
Idea: This is a circular matrix, which can be replaced by the time of O (N ^ 2 ).
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;typedef long long ll;const int maxn = 505;int n, m, d, k;ll ans[maxn], matrix[maxn];ll c[maxn+5];void mul(ll a[], ll b[]) {memset(c, 0, sizeof(c));for (int i = 0; i < n; i++) for (int j = 0; j < n; j++)c[i] += a[j] * b[(i-j+n) % n];for (int i = 0; i < n; i++) b[i] = c[i] % m;}int main() {while (scanf("%d%d%d%d", &n, &m, &d, &k) != EOF) {memset(ans, 0, sizeof(ans));memset(matrix, 0, sizeof(matrix));for (int i = 0; i < n; i++) cin>>ans[i];matrix[0] = 1;for (int i = 1; i <= d; i++) matrix[i] = matrix[n - i] = 1;while (k) {if (k & 1) mul(matrix, ans);mul(matrix, matrix);k >>= 1;}for (int i = 0; i < n - 1; i++) printf("%lld ", ans[i]);printf("%lld\n", ans[n-1]);}return 0;}
Ultraviolet A-1386 Cellular Automaton