洛谷P4562 [JXOI2018]游戏(组合数学)

题意

题目链接

Sol

这个题就比较休闲了。

\(t(p)\)显然等于最后一个没有约数的数的位置,那么我们可以去枚举一下。

设没有约数的数的个数有\(cnt\)个

因此总的方案为\(\sum_{i=cnt}^{r-l+1} C_{i-1}^{cnt-1} cnt! (r - l + 1 - cnt)!\)

稍微有点卡常,筛的时候加一下剪枝

#include<bits/stdc++.h>
#define Fin(x) freopen(#x".in", "r", stdin);
using namespace std;
const int MAXN = 1e7 + 10, mod = 1e9 + 7;
template<typename A, typename B> inline bool chmax(A &x, B y) {return x < y ? x = y, 1 : 0;}
template<typename A, typename B> inline bool chmin(A &x, B y) {return x > y ? x = y, 1 : 0;}
template<typename A, typename B> inline A mul(A x, B y) {return 1ll * x * y % mod;}
template<typename A, typename B> inline void add2(A &x, B y) {x = x + y >= mod ? x + y - mod : x + y;}
inline int read() {
char c = getchar(); int x = 0, f = 1;
while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
int fac[MAXN], ifac[MAXN], vis[MAXN], cnt;
int fp(int a, int p) {
int base = 1;
while(p) {
if(p & 1) base = mul(base, a);
a = mul(a, a); p >>= 1;
}
return base;
}
int C(int N, int M) {
return mul(fac[N], mul(ifac[M], ifac[N - M]));
}
int main() {
int l = read(), r = read();
for(int i = l; i <= r; i++) {
if(vis[i]) continue;
if(!vis[i]) cnt++;
for(int j = i + i; j <= r; j += i)
vis[j] = 1;
}
fac[0] = 1;
for(int i = 1; i <= r; i++) fac[i] = mul(i, fac[i - 1]);
ifac[r] = fp(fac[r], mod - 2);
for(int i = r; i; i--) ifac[i - 1] = mul(ifac[i], i);
int ans = 0;
for(int i = cnt; i <= r - l + 1; i++)
add2(ans, mul(i, mul(C(i - 1, cnt - 1), mul(fac[cnt], fac[r - l + 1 - cnt]))));
cout << ans;
return 0;
}
上一篇:【Luogu3457】POW-The Flood(并查集)


下一篇:大厂高级工程师面试必问系列:Java动态代理机制和实现原理详解