题解 P3172 【[CQOI2015]选数】

· · 题解

首先,进行如下处理:

1、如果LK的倍数,那么把L变为\frac{L}{K},否则变为\lfloor\frac{L}{K}\rfloor+1

2、把H变成\lfloor\frac{H}{K}\rfloor

这样子容易得出,现在要求的就是在[L,H]之间,选数N次使选出的数最大公约数为1的方案数。

现在,用f[i]表示选出的数的最大公约数i且选出的数不全相同的方案数。此时先求出[L,H]之间i的倍数的个数x,暂时令f[i]=x^N-x

但此时得到的f[i]实际上是含有公约数i的方案数,不是最大公约数为i的方案数。但是可以发现,此时的f[i]包含有最大公约数为i,2i,3i,...的方案数。这时候使用容斥原理:假设已经知道了f[2i],f[3i],...最终结果,那么就把f[i]分别减去f[2i],f[3i],...,就可以得到f[i]的最终结果。倒着推一遍。

特殊情况:L=1时可以所有的数都选1。所以L=1时答案要加1

代码:

#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
inline int read() {
    int res = 0; bool bo = 0; char c;
    while (((c = getchar()) < '0' || c > '9') && c != '-');
    if (c == '-') bo = 1; else res = c - 48;
    while ((c = getchar()) >= '0' && c <= '9')
        res = (res << 3) + (res << 1) + (c - 48);
    return bo ? ~res + 1 : res;
}
const int N = 1e5 + 5, PYZ = 1e9 + 7;
int n, K, L, H, f[N];
int qpow(int a, int b) {
    int res = 1;
    while (b) {
        if (b & 1) res = 1ll * res * a % PYZ;
        a = 1ll * a * a % PYZ;
        b >>= 1;
    }
    return res;
}
int main() {
    int i, j; n = read(); K = read(); L = read(); H = read();
    if (L % K) L = L / K + 1; else L /= K; H /= K;
    if (L > H) return puts("0"), 0;
    for (i = 1; i <= H - L; i++) {
        int l = L, r = H;
        if (l % i) l = l / i + 1; else l /= i; r /= i;
        if (l > r) continue;
        f[i] = (qpow(r - l + 1, n) - (r - l + 1) + PYZ) % PYZ;
    }
    for (i = H - L; i; i--) for (j = (i << 1); j <= H - L; j += i)
        f[i] = (f[i] - f[j] + PYZ) % PYZ;
    if (L == 1) (f[1] += 1) %= PYZ; cout << f[1] << endl;
    return 0;
}