Bzoj3930: [CQOI 2015] 选数 & COGS2699: [CQOI 2015] 选数加强版

时间:2021-07-26 04:13:56

题面

Bzoj

COGS加强版

Sol

非加强版可以枚举AC这里不再讲述


设\(f(i)\)表示在\([L, H]\)取\(N\)个,\(gcd为i\)的方案数

\(F(i)=\sum_{i|d}f(d)\)表示\([L,H]\)取\(N\)个,\(gcd为i\)的倍数的方案数

易得\(F(i)=(\lfloor\frac{H}{i}\rfloor-\lfloor\frac{L-1}{i}\rfloor)^N\)

直接莫比乌斯反演得到\(f(K)=\sum_{K|d}\mu(\frac{d}{K})F(d)\)

把\(\frac{d}{K}\)替换掉\(f(K)=\sum_{i=1}^{\lfloor\frac{H}{K}\rfloor}\mu(i)F(K*i)\)

分块\(F(K*i)\)杜教筛出\(\mu\)的前缀和就可以了

# include <bits/stdc++.h>
# define RG register
# define IL inline
# define Fill(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long ll;
const int _(1e6 + 1), Zsy(1e9 + 7); IL ll Read(){
RG ll x = 0, z = 1; RG char c = getchar();
for(; c < '0' || c > '9'; c = getchar()) z = c == '-' ? -1 : 1;
for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
return x * z;
} int prime[_], mu[_], s[_], num, L, H, N, K, MAXN;
map <int, int> Mu;
bool isprime[_]; IL ll Pow(RG ll x, RG ll y){
RG ll ret = 1;
for(; y; y >>= 1, x = x * x % Zsy) if(y & 1) ret = ret * x % Zsy;
return ret;
} IL void Prepare(){
isprime[1] = 1; mu[1] = 1;
for(RG int i = 2; i < MAXN; ++i){
if(!isprime[i]){ prime[++num] = i; mu[i] = -1; }
for(RG int j = 1; j <= num && i * prime[j] < MAXN; ++j){
isprime[i * prime[j]] = 1;
if(i % prime[j]) mu[i * prime[j]] = -mu[i];
else{ mu[i * prime[j]] = 0; break; }
}
mu[i] += mu[i - 1];
}
} IL int SumMu(RG int n){
if(n < MAXN) return mu[n];
if(Mu[n]) return Mu[n];
RG int ans = 1;
for(RG int i = 2, j; i <= n; i = j + 1){
j = n / (n / i);
ans -= 1LL * (j - i + 1) * SumMu(n / i) % Zsy;
ans = (ans + Zsy) % Zsy;
}
return Mu[n] = ans;
} int main(RG int argc, RG char* argv[]){
N = Read(); K = Read(); L = (Read() - 1) / K; H = Read() / K;
RG int ans = 0, lst = 0, now; MAXN = min(H + 1, _); Prepare();
for(RG int i = 1, j; i <= H; i = j + 1){
j = H / (H / i); if(L / i) j = min(j, L / (L / i));
now = SumMu(j);
ans += 1LL * (now - lst) * Pow(H / i - L / i, N) % Zsy;
ans = (ans % Zsy + Zsy) % Zsy; lst = now;
}
printf("%d\n", ans);
return 0;
}