UVA - 1386 Cellular Automaton


题目:点击打开链接

题意:一个细胞自动机包含n个格子,每个格子的值都会变成它距离不超过d的所有格子的值,求最后的结果

思路:这个是循环矩阵,可以用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;
}


你可能感兴趣的:(UVA - 1386 Cellular Automaton)