当前位置: 代码迷 >> 综合 >> UVA 1386 Cellular Automaton(循环矩阵)
  详细解决方案

UVA 1386 Cellular Automaton(循环矩阵)

热度:77   发布时间:2023-12-08 11:11:16.0

题目链接:
UVA 1386 Cellular Automaton
题意:
给一个n个数组成的数环,每次取每个数左右范围d的所有数(包括本身和距离是d的数)相加和mod m生成新的数,
问操作k次后的数环是怎样的?
分析:
主要是n太大了,n<=500,拿样例

5 3 1 1
1 2 2 1 2
来说。可以构造矩阵,其中d=1.

| 1 1 0 0 1 |
| 1 1 1 0 0 |
| 0 1 1 1 0 |
| 0 0 1 1 1 |
| 1 0 0 1 1 |

但是如果构造500*500的矩阵会RE,而如果用数组模拟矩阵乘法和快速幂又会TLE(亲测)。如果能观察到这个矩阵是循环矩阵就好解决了,也就是每次相乘后的矩阵每行数字相对顺序都是一样的,只是产生了相对位移,上面的构造矩阵就是很直观的例子。将上面的矩阵自己乘自己后得到:

| 3 2 1 1 2 |
| 2 3 2 1 1 |
| 1 2 3 2 1 |
| 1 1 2 3 2 | 
| 2 1 1 2 3 |

所以可以将二维矩阵压缩为一维每次只保留第一行数字,这样时间复杂度就变成了 O(n?n?logk) (二维矩阵的时间复杂度是 O(n?n?n?logk) ),通过手动模拟原始矩阵的乘法可以到这个式子:
A[j]?B[(j?i+n) % n]
其中下标都是从0开始到 n?1
只要把快速幂的结果按照同样的规律乘上原始数列就能得到最终数列了。

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
using namespace std;
typedef long long ll;
const int MAX_N = 510;int n, mod, d, K;
ll C[MAX_N], D[MAX_N], M[MAX_N], ret[MAX_N], ans[MAX_N];inline void mul(ll *arr1, ll *arr2) { // arr2 = arr1 * arr2memset(ret, 0, sizeof (ret));for (int i = 0; i < n; ++i) {for (int j = 0; j < n; ++j) {ret[i] += arr1[j] * arr2[(j - i + n) % n] % mod;if (ret[i] >= mod) ret[i] -= mod; }}memcpy(arr2, ret, sizeof (ret));
}void Qpower() {memset (M, 0, sizeof(M));M[0] = 1;while (K) {if (K & 1) mul(C, M);mul(C, C);K >>= 1;}
}int main() {while (~scanf("%d%d%d%d", &n, &mod, &d, &K)){for (int i = 0; i < n; i++) {ll x;scanf("%lld", &x);D[i] = x % mod;}memset (C, 0, sizeof (C));for (int i = 0; i < 2 * d + 1; i++) {C[(n - d + i) % n] = 1;}Qpower();memset (ans, 0, sizeof (ans));for (int i = 0; i < n; i++) {for (int j = 0; j < n; j++) {int ind = (j - i + n) % n;ans[i] += D[j] * M[(j - i + n) % n] % mod;if (ans[i] >= mod) ans[i] -= mod;}}for (int i = 0; i < n; i++) {if (i) printf(" ");printf("%lld", ans[i]);}printf("\n");}return 0;
}