【模板】组合数取模

\(N \le 2000, M \le 2000\)
直接利用递推式预处理即可。
代码如下

#include <bits/stdc++.h>

using namespace std;

const int mod = 1e9 + 7;

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0), cout.tie(0);
	int n;
	cin >> n;
	static int f[2010][2010];
	for (int i = 0; i <= 2000; i++) {
		f[i][0] = 1;
	}
	for (int i = 1; i <= 2000; i++) {
		for (int j = 1; j <= 2000; j++) {
			f[i][j] = (f[i - 1][j] + f[i - 1][j - 1]) % mod;
		}
	}
	while (n--) {
		int a, b;
		cin >> a >> b;
		cout << f[a][b] << endl;
	}
	return 0;
}

\(N, M \le 1e5\)
预处理出阶乘和阶乘的逆元,利用组合数的定义直接回答。

#include <bits/stdc++.h>

using namespace std;

typedef long long LL;

const int mod = 1e9 + 7;
const int maxn = 1e5 + 10;

LL fpow(LL a, LL b) {
	LL ret = 1 % mod;
	for (; b; b >>= 1, a = a * a % mod) {
		if (b & 1) {
			ret = ret * a % mod;
		}
	}
	return ret;
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0), cout.tie(0);
	int n;
	cin >> n;
	vector<LL> inv(maxn), fac(maxn);
	auto prework = [&]() {
		fac[0] = 1;
		for (int i = 1; i <= 1e5; i++) {
			fac[i] = fac[i - 1] * i % mod;
		}
		inv[1e5] = fpow(fac[1e5], mod - 2);
		for (int i = 1e5 - 1; i >= 0; i--) {
			inv[i] = inv[i + 1] * (i + 1) % mod;
		}
	};
	prework();
	auto get = [&](int a, int b) {
		return fac[a] * inv[a - b] % mod * inv[b] % mod;
	};
	while (n--) {
		int a, b;
		cin >> a >> b;
		cout << get(a, b) << endl;
	}
	return 0;
}
/*
(a, b) = a! / ((a - b)! * b!)
a! = a * (a - 1)!
a!' * a = (a - 1)!'
*/

\(N, M \le 1e18, p \le 1e5,p \in prime\)
预处理出 \(1...p\) 的阶乘和阶乘的逆元,用卢卡斯定理进行回答。
代码如下

#include <bits/stdc++.h>

using namespace std;

typedef long long LL;

LL fpow(LL a, LL b, LL c) {
	LL ret = 1 % c;
	for (; b; b >>= 1, a = a * a % c) {
		if (b & 1) {
			ret = ret * a % c;
		}
	}
	return ret;
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0), cout.tie(0);
	int n;
	cin >> n;
	while (n--) {
		LL a, b, p;
		cin >> a >> b >> p;
		vector<LL> inv(p + 1), fac(p + 1);
		fac[0] = 1;
		for (int i = 1; i <= p; i++) {
			fac[i] = fac[i - 1] * i % p;
		}
		inv[p - 1] = fpow(fac[p - 1], p - 2, p);
		for (int i = p - 2; i >= 0; i--) {
			inv[i] = inv[i + 1] * (i + 1) % p;
		}
		auto C = [&](LL x, LL y) -> LL {
			if (x < y) {
				return 0;
			}
			return fac[x] * inv[x - y] % p * inv[y] % p;
		};
		function<LL(LL, LL)> Lucas = [&](LL x, LL y) -> LL {
			if (y == 0) {
				return 1;
			}
			return C(x % p, y % p) * Lucas(x / p, y / p) % p;
		};
		cout << Lucas(a, b) << endl;
	}
	return 0;
}
posted @ 2019-09-29 14:58  shellpicker  阅读(293)  评论(0编辑  收藏  举报