跳到正文

题解

题解:P2231 [HNOI2002] 跳蚤

11400F约 5 分钟
原文
文章信息与版本

文章信息

发布
2024年12月31日
收录
2026年10月21日
更新
2026年11月12日
篇幅
约 5 分钟
获赞
1
题目
P2231

版本

  1. v1当前

P2231 跳蚤 题解

不知道好不好的阅读体验


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

a1x1+a2x2+⋯+anxn+mxn+1=1a_1x_1 + a_2x_2 + \cdots + a_nx_n + mx_{n+1} = 1

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

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

设 a1,a2,⋯ana_1, a_2, \cdots a_n 为不全为 00 的整数,则存在整数 x1,x2,⋯ ,xnx_1, x_2, \cdots , x_n,使得 a1x1+a2x2+⋯anxn=gcd⁡(a1,a2,⋯an)a_1x_1 + a_2x_2 + \cdots a_nx_n = \gcd(a_1, a_2, \cdots a_n)。

(节选自 OI-Wiki)

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

即让我们求:

∑a1=0m∑a2=0m⋯∑an=0m[gcd⁡(a1,a2,⋯ ,an,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]

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

∑a1=1m∑a2=1m⋯∑an=1m[gcd⁡(a1,a2,⋯ ,an,m)=1]\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]

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

∑a1=1m∑a2=1m⋯∑an=1m∑d∣gcd(a1,a2,⋯an,m)μ(d)=∑a1=1m∑a2=1m⋯∑an=1m∑d∣a1∧d∣a2∧⋯∧d∣an∧d∣mμ(d)\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)

即:

∑d∣mμ(d)⋅∑a1=1⌊md⌋∑a2=1⌊md⌋⋯∑an=1⌊md⌋1=∑d∣mμ(d)⋅(⌊md⌋)n\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}

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

Code:

C++
#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';
}
原文