【数论】——组合数
- 公式:
C
a
b
=
a
!
b
!
?
(
a
?
m
)
!
C_{a}^{b} = \frac{a!}{b!*(a-m)!}
Cab?=b!?(a?m)!a!? a,b的范围,以及n(询问次数)进行分类求解。
n在
1
e
4
?
1
e
5
1e4-1e5
1e4?1e5,a,b在
1
e
3
1e3
1e3
- 由于,询问次数过多,而a,b范围很小,因此采用离线处理所有
C
a
b
C_{a}^{b}
Cab? 的方式进行求解。
- 利用递推:
C
a
b
=
C
a
?
1
b
?
1
+
C
a
?
1
b
C_{a}^{b} = C_{a-1}^{b-1}+C_{a-1}^{b}
Cab?=Ca?1b?1?+Ca?1b? - 代码
const int mod = 1e9 + 7;
int dp[N][N];
int solve_1()
{
for (int i = 0; i < N; i++)
for (int j = 0; j <= i; j++) {
if (!j)
dp[i][j] = 1;
dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j]) % mod;
}
}
n在
1
e
4
?
1
e
5
1e4-1e5
1e4?1e5,a,b在
1
e
5
1e5
1e5
- 由于,询问次数过多,同时a,b范围比较大,因此采用离线处理所有
C
a
b
C_{a}^{b}
Cab? 的方式进行求解会tle。
- 但是可以通过离线处理所有a,b的阶乘来达到快速求解的目的,同时利用快速幂,求分母上的逆元
- 代码
const int mod = 1e9 + 7;
int fact[N], infact[N];
int quickmi(int a, int k)
{
long long res = 1;
while (k) {
if (k & 1) {
res = (long long)res * a % mod;
}
a = (long long)a * a % mod;
k >>= 1;
}
return res;
}
void solve_2()
{
fact[0] = infact[0] = 1;
for (int i = 1; i < N; i++) {
fact[i] = (long long)fact[i - 1] * i % mod;
infact[i] = (long long)infact[i - 1] * quickmi(i, mod - 2) % mod;
}
}
n在
100
100
100以内,a,b在
1
e
16
1e16
1e16+
运用lucas定理求解:(p为给定的模数)
C
a
b
≡
C
a
?
m
o
d
?
p
b
?
m
o
d
?
p
+
C
a
p
a
p
(
m
o
d
?
p
)
C_{a}^{b} \equiv C_{a\ mod\ p}^{b\ mod\ p}+C_{\frac{a}{p}}^{\frac{a}{p}}\qquad (mod\ p)
Cab?≡Ca?mod?pb?mod?p?+Cpa?pa??(mod?p)
int quickmi(int a, int k, int p)
{
int res = 1;
while (k) {
if (k & 1) {
res = (long long)res * a % p;
}
a = (long long)a * a % p;
k >>= 1;
}
return res;
}
int solve(int a, int b, int p)
{
if (b > a)
return 0;
int res = 1;
for (int i = 1, j = a; i <= b; i++, j--) {
res = (long long)res * j % p;
res = (long long)res * quickmi(i, p - 2, p) % p;
}
return res;
}
int lucas(long long a, long long b, int p)
{
if (a < p && b < p)
return solve(a, b, p);
return (long long)solve(a % p, b % p, p) * lucas(a / p, b / p, p) % p;
}
没有模数的高精度写法
-
思路: -
代码
int primes[N], cnt;
int sum[N];
bool st[N];
void get_primes(int n)
{
for (int i = 2; i <= n; i++) {
if (!st[i])
primes[cnt++] = i;
for (int j = 0; primes[j] <= n / i; j++) {
st[primes[j] * i] = true;
if (i % primes[j] == 0)
break;
}
}
}
int get(int n, int p)
{
int res = 0;
while (n) {
res += n / p;
n /= p;
}
return res;
}
vector<int> mul(vector<int> a, int b)
{
vector<int> c;
int t = 0;
for (int i = 0; i < a.size(); i++) {
t += a[i] * b;
c.push_back(t % 10);
t /= 10;
}
while (t) {
c.push_back(t % 10);
t /= 10;
}
return c;
}
int main()
{
int a, b;
cin >> a >> b;
get_primes(a);
for (int i = 0; i < cnt; i++) {
int p = primes[i];
sum[i] = get(a, p) - get(a - b, p) - get(b, p);
}
vector<int> res;
res.push_back(1);
for (int i = 0; i < cnt; i++)
for (int j = 0; j < sum[i]; j++)
res = mul(res, primes[i]);
for (int i = res.size() - 1; i >= 0; i--)
printf("%d", res[i]);
puts("");
return 0;
}
|