题解:P2231 [HNOI2002] 跳蚤

· · 题解

P2231 跳蚤 题解

不知道好不好的阅读体验

这道题就是让我们求,给定序列 a 的范围 0 \le a_i \le m,使方程

a_1x_1 + a_2x_2 + \cdots + a_nx_n + mx_{n+1} = 1

有整数解的 a 序列的可能的不同的取值个数。

根据裴蜀定理的多个整数的推广:

设 a_1, a_2, \cdots a_n 为不全为 0 的整数,则存在整数 x_1, x_2, \cdots , x_n,使得 a_1x_1 + a_2x_2 + \cdots a_nx_n = \gcd(a_1, a_2, \cdots a_n)。

(节选自 OI-Wiki)

于是我们可以推断:\gcd(a_1, a_2, \cdots a_n, m) = 1。

即让我们求:

\sum_{a_1 = 0}^{m} \sum_{a_2 = 0}^{m} \cdots \sum_{a_n=0}^{m} [\gcd(a_1, a_2, \cdots, a_n, m) = 1]

因为序列中只要有一个 0,这个序列的公因数就为 0。即可以转为:

\sum_{a_1 = 1}^{m} \sum_{a_2 = 1}^{m} \cdots \sum_{a_n=1}^{m} [\gcd(a_1, a_2, \cdots, a_n, m) = 1]

根据莫比乌斯函数性质,则将其转为:

\sum_{a_1 = 1}^{m} \sum_{a_2 = 1}^{m} \cdots \sum_{a_n=1}^{m}\sum_{d \mid gcd(a_1, a_2, \cdots a_n, m)} \mu(d) \\ = \sum_{a_1 = 1}^{m} \sum_{a_2 = 1}^{m} \cdots \sum_{a_n=1}^{m}\sum_{d \mid a_1 \land d\mid a_2 \land \cdots \land d \mid a_n \land d \mid m} \mu(d)

即:

\sum_{d \mid m} \mu(d)\cdot\sum_{a_1 = 1}^{\lfloor\frac{m}{d}\rfloor} \sum_{a_2 = 1}^{\lfloor\frac{m}{d}\rfloor} \cdots \sum_{a_n = 1}^{\lfloor\frac{m}{d}\rfloor} 1 \\ = \sum_{d \mid m} \mu(d) \cdot (\lfloor\frac{m}{d}\rfloor)^{n}

而因为当 d 为 1 或没有平方项的质数的乘积时,\mu(d) 才对答案有贡献(即值为 1 或 -1。没有贡献的值就是 0,因为它根本影响不了答案)。所以我们可以先将 m 质因数分解,然后枚举 d 包含了 m 的哪些质因子。\mu(d) 因为有枚举的质因数个数,所以可以现算。然后后面的那个 n 次方的玩意直接快速幂算出来即可。

Code:

#include<bits/stdc++.h>
using namespace std;
const int N = 20;
int n, m;
int prime[N], primecnt;
void divide(int x){
    int lim = sqrt(x);
    for(int i=2;i<=lim && i<=x;i++){
        if(x%i==0){
            prime[++primecnt] = i;
            while(x%i==0) x/=i;
        }
    }
    if(x!=1) prime[++primecnt] = x;
}
typedef long long ll;
ll ans = 0;
ll ksm(ll bas, ll x){
    ll ans = 1;
    while(x){
        if(x&1) ans = ans * bas;
        bas = bas * bas;
        x >>= 1;
    }
    return ans;
}
void dfs(int x, int mu, int m_d){
    // int d;
    ans += mu * ksm(m_d, n);
    for(int i=x;i<=primecnt;i++){
        dfs(i+1, mu*(-1), m_d / prime[i]);
    }
}
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    cin>>n>>m;
    divide(m);
    dfs(1, 1, m);
    cout<<ans<<'\n';
}