【Codeforces621E】Wet Shark and Blocks【矩阵乘法】【DP】

http://codeforces.com/problemset/problem/621/E


trans[i][j]表示余数从i到j的方案数,那么有trans[i][j] = ∑trans[i][k]*trans[k][j],显然是个矩阵乘法,用快速幂优化一下就好了。


/* Footprints In The Blood Soaked Snow */
#include <cstdio>

typedef long long LL;

const int maxn = 105, maxm = 15, p = 1000000007;

int n, b, k, x, cnt[maxm];

struct _mat {
	LL num[maxn][maxn];
} E, trans;

inline int iread() {
	int f = 1, x = 0; char ch = getchar();
	for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
	for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
	return f * x;
}

inline _mat mul(_mat &A, _mat &B) {
	_mat C;
	for(int i = 0; i < x; i++) for(int j = 0; j < x; j++) {
		C.num[i][j] = 0;
		for(int k = 0; k < x; k++) C.num[i][j] = (C.num[i][j] + A.num[i][k] * B.num[k][j] % p) % p;
	}
	return C;
}

inline _mat qpow(_mat &A, int n) {
	_mat ans = E;
	for(_mat t = A; n; n >>= 1, t = mul(t, t)) if(n & 1) ans = mul(ans, t);
	return ans;
}

int main() {
	n = iread(); b = iread(); k = iread(); x = iread();
	for(int i = 1; i <= n; i++) cnt[iread() % x]++;

	for(int i = 0; i < x; i++) E.num[i][i] = 1;
	for(int i = 0; i < x; i++) for(int j = 0; j <= 9; j++)
		trans.num[i][(i * 10 + j) % x] = (trans.num[i][(i * 10 + j) % x] + cnt[j]) % p;

	_mat ans = qpow(trans, b);

	printf("%I64d\n", ans.num[0][k]);
	return 0;
}


你可能感兴趣的:(dp,矩阵乘法)