板刷 组合计数(洗澡间题单)
yuezhongyan · · 个人记录
前言
也是在退役之前开这个了啊。
T1 P3197 [HNOI2008] 越狱
前面的橙题太逆天了,就不放了。
solution
正难则饭。
注意到,一共有
code
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int mod = 100003;
int qik(int a, int b) {
int res = 1;
while (b) {
if (b & 1) res = res * a % mod;
a = a * a % mod;
b >>= 1;
}
return res;
}
signed main(void) {
int n, r;
cin >> n >> r;
int sum1 = qik(n, r), sum2 = n * qik(n - 1, r - 1) % mod;
cout << (sum1 - sum2 + 3 * mod) % mod << '\n';
return 0;
}
T2P5520 [yLOI2019] 青原樱
去听青原樱了。
solution
考虑先求花的排列:显然为
code
#include <bits/stdc++.h>
#define int long long
using namespace std;
int n, m, p, type;
signed main(void) {
cin >> type >> n >> m >> p;
int ans = 1;
for (int i = n - 2 * m + 2; i <= n - m + 1; i ++ ) ans = ans * i % p;
cout << ans << '\n';
return 0;
}
T3 P1313 [NOIP 2011 提高组] 计算系数
solution
考虑二项式展开:
-
(a+b)^n = \sum_{k=0}^n C_n^k a^kb^{n-k}
答案转化为求
code
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int mod = 10007, N = 1005;
int a, b, k, n, m, fac[N], inv[N];
int qik(int x, int y) {
int res = 1;
while (y) {
if (y & 1) res = res * x % mod;
x = x * x % mod;
y >>= 1;
}
return res % mod;
}
int comb(int x, int y) {
return fac[y] * inv[x] % mod * inv[y - x] % mod;
}
signed main(void) {
cin >> a >> b >> k >> n >> m;
fac[1] = 1;
for (int i = 2; i < N; i ++ ) fac[i] = fac[i - 1] * i % mod;
for (int i = 1; i < N; i ++ ) inv[i] = qik(fac[i], mod - 2);
cout << comb(n, n + m) * qik(a, n) % mod * qik(b, m) % mod << '\n';
return 0;
}
T4 P4071 [SDOI2016] 排列计数
solution
考虑先排好排列正确的数,共有
剩下的数转化为错排问题,考虑一种类似 dp 的思路。
设
- 若前面的数已经全部错排好,当前的
i 可以和任意一个交换,生成的序列一定满足错排,即d_i \gets (i - 1) \times d_{i-1} - 若前面的数有一个没错排好,当前的
i 一定要和没错排好的数交换,生成的序列也一定错排,即d_i \gets (i-1) \times d_{i-2}
综上:
code
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 1e6 + 5, mod = 1e9 + 7;
int T, m, n, fac[N], inv[N], d[N];
int qik(int a, int b) {
int res = 1;
while (b) {
if (b & 1) res = res * a % mod;
a = a * a % mod;
b >>= 1;
}
return res;
}
int comb(int x, int y) {
return fac[y] * inv[x] % mod * inv[y - x] % mod;
}
signed main(void) {
fac[0] = inv[0] = 1, d[1] = 0, d[2] = 1, d[0] = 1;
for (int i = 1; i < N; i ++ ) fac[i] = fac[i - 1] * i % mod;
for (int i = 1; i < N; i ++ ) inv[i] = qik(fac[i], mod - 2);
for (int i = 3; i < N; i ++ ) d[i] = (i - 1) * ((d[i - 1] + d[i - 2]) % mod) % mod;
cin >> T;
while (T -- ) {
cin >> n >> m;
cout << comb(m, n) * d[n - m] % mod << '\n';
}
return 0;
}