【BZOJ4870】【六省联考2017】组合数问题(矩阵快速幂)

Description

计算:
( ∑ i = 0 + ∞ ( n k i k + r ) )   m o d   p \left( \sum_{i=0}^{+\infty} \binom{nk}{ik+r} \right)\bmod p (i=0+(ik+rnk))modp

n ≤ 1 0 9 , 0 ≤ r < k ≤ 50 , 2 ≤ p ≤ 2 30 − 1 n\le 10^9, 0\le r < k \le 50, 2\le p\le 2^{30}-1 n109,0r<k50,2p2301


Solution

我们要计算的是在 n k nk nk个物体中选择一些物品使得数量   m o d   k = r \bmod k=r modk=r

考虑一个DP, f i f_i fi表示当前物品中有多少种选择方案使得数量   m o d   k = i \bmod k=i modk=i,转移显然。

用矩阵快速幂优化即可。


Code

/************************************************
 * Au: Hany01
 * Prob: BZOJ4870
 * Email: [email protected] & [email protected]
 * Inst: Yali High School
************************************************/

#include

using namespace std;

typedef long long LL;
typedef long double LD;
typedef pair<int, int> PII;
#define Rep(i, j) for (register int i = 0, i##_end_ = (j); i < i##_end_; ++ i)
#define For(i, j, k) for (register int i = (j), i##_end_ = (k); i <= i##_end_; ++ i)
#define Fordown(i, j, k) for (register int i = (j), i##_end_ = (k); i >= i##_end_; -- i)
#define Set(a, b) memset(a, b, sizeof(a))
#define Cpy(a, b) memcpy(a, b, sizeof(a))
#define X first
#define Y second
#define PB(a) push_back(a)
#define MP(a, b) make_pair(a, b)
#define SZ(a) ((int)(a).size())
#define ALL(a) a.begin(), a.end()
#define INF (0x3f3f3f3f)
#define INF1 (2139062143)
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define y1 wozenmezhemecaia

template <typename T> inline bool chkmax(T &a, T b) { return a < b ? a = b, 1 : 0; }
template <typename T> inline bool chkmin(T &a, T b) { return b < a ? a = b, 1 : 0; }

template <typename T> inline T read() {
	static T _, __; static char c_;
    for (_ = 0, __ = 1, c_ = getchar(); c_ < '0' || c_ > '9'; c_ = getchar()) if (c_ == '-') __ = -1;
    for ( ; c_ >= '0' && c_ <= '9'; c_ = getchar()) _ = (_ << 1) + (_ << 3) + (c_ ^ 48);
    return _ * __;
}
//EOT


const int maxn = 55;

int n, MOD, k, r;

struct Matrix {
	int x, y, ret[maxn][maxn];
	inline int* operator [] (int x) { return ret[x]; }
	inline void identity() { x = y = k, Set(ret, 0); Rep(i, k) ret[i][i] = 1; }
};

inline Matrix operator * (Matrix A, Matrix B) {
	static Matrix C;
	C.x = A.x, C.y = B.y;
	Rep(i, C.x) Rep(j, C.y) {
		C[i][j] = 0;
		Rep(k, A.y) C[i][j] = (C[i][j] + (LL)A[i][k] * B[k][j] % MOD) % MOD;
	}
	return C;
}

inline Matrix Pow(Matrix a, LL b) {
	Matrix ans;
	for (ans.identity(); b; b >>= 1, a = a * a) if (b & 1) ans = ans * a;
	return ans;
}

int main()
{
#ifdef hany01
	freopen("bzoj4870.in", "r", stdin);
	freopen("bzoj4870.out", "w", stdout);
#endif

	n = read<int>(), MOD = read<int>(), k = read<int>(), r = read<int>();

	Matrix A, Trans;
	A.x = k, A.y = 1, A[0][0] = 1;
	Trans.x = Trans.y = k;
	Rep(i, k) ++ Trans[i][i], ++ Trans[i][(i + k - 1) % k];
	A = Pow(Trans, (LL)n * k) * A;
	printf("%d\n", A[r][0]);

	return 0;
}

你可能感兴趣的:(BZOJ,省选,矩阵快速幂,DP)