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

题面

Bzoj
COGS加强版

Sol

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


f(i) 表示在 [L,H] N 个, gcdi 的方案数
F(i)=i|df(d) 表示 [L,H] N 个, gcdi 的倍数的方案数
易得 F(i)=(HiL1i)N
直接莫比乌斯反演得到 f(K)=K|dμ(dK)F(d)

dK 替换掉 f(K)=HKi=1μ(i)F(Ki)

分块 F(Ki) 杜教筛出 μ 的前缀和就可以了

# include 
# 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;
}

你可能感兴趣的:(反演与容斥,狄利克雷卷积和杜教筛)