组合数
从
根据公式可以预处理,把所有范围内的阶乘和阶乘的逆元求出来
条件:
因为取模的数为素数,所以可以用费马小定理求乘法逆元
组合数问题
题目描述
给出
其中
输入格式
输入的第一行是两个整数,分别表示询问的次数
接下来
输出格式
为了避免输出过大,请你输出一行一个整数,表示所有询问的结果的按位异或和。
样例 #1
样例输入 #1
3 5
3 3
4 2
5 3样例输出 #1
13提示
样例 1 解释
三组询问的答案依次是
数据规模与约定
对
提示
请注意大量的数据读入对程序效率造成的影响,选择合适的读入方式,避免超时。
题解
预处理
c++
#include <bits/stdc++.h>
using i64 = long long;
constexpr int P = 998244353;
constexpr int L = 5E6 + 5;
i64 fac[L + 1], invfac[L + 1];
i64 sumbinom[L + 1][7];
i64 binom(i64 n, i64 m) {
if (n < m || m < 0) {
return 0;
}
return 1LL * fac[n] * invfac[m] % P * invfac[n - m] % P;
}
i64 power(i64 a, i64 b) {
i64 res = 1;
for (; b; b /= 2, a = 1LL * a * a % P) {
if (b % 2) {
res = 1LL * res * a % P;
}
}
return res;
}
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
fac[0] = 1;
for (int i = 1; i <= L; i++) {
fac[i] = 1LL * fac[i - 1] * i % P;
}
invfac[L] = power(fac[L], P - 2);
for (int i = L; i; i--) {
invfac[i - 1] = 1LL * invfac[i] * i % P;
}
int t, n;
std::cin >> t >> n;
i64 ans = 0;
while (t--) {
i64 x, y;
std::cin >> x >> y;
ans ^= binom(x, y);
}
std::cout << ans << "\n";
return 0;
}组合恒等式
也是杨辉三角
考虑第n个元素取或不取
若取,则前n-1个元素中取m-1个
若取,则前n-1个元素中取m个
有时候题目数据范围有负数,那么两边的边界一定要取**-INF**
c++
for(int i=1;i<=2000;i++)
c[i][0]=c[i][i]=1;//杨辉三角边界等于1
for(int i=2;i<=2000;i++)
for(int j=1;j<i;j++)
c[i][j]=(c[i-1][j]+c[i-1][j-1]);//杨辉三角递推式二项式定理
组合数与排列数
枚举金额,再尝试每种硬币
关心不同排列
c++
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
constexpr int N = 1E6 + 5;
constexpr int mod = 1E9 + 7;
i64 a[105], dp[N];
void solve() {
int n, x;
cin >> n >> x;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
dp[0] = 1;
for (int i = 1; i <= x; i++) {
for (int j = 1; j <= n; j++) {
if (i >= a[j]) {
dp[i] = dp[i] + dp[i - a[j]] % mod;
}
}
}
cout << dp[x] % mod << "\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int _ = 1;
// cin >> _;
while (_--) {
solve();
}
return 0;
}组合数
不关心排列,顺序不同算一种组合
c++
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
constexpr int N = 1E6 + 5;
constexpr int mod = 1E9 + 7;
i64 a[105], dp[N];
void solve() {
int n, x;
cin >> n >> x;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
dp[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = a[i]; j <= x; j++) {
dp[j] = dp[j] + dp[j - a[i]] % mod; // 当前能组成的方案数加上之前dp[j-a[i]]的组成方案数
//cout << j << ":" << dp[j] << " ";
}
//cout << "\n";
}
cout << dp[x] % mod << "\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int _ = 1;
// cin >> _;
while (_--) {
solve();
}
return 0;
}