BZOJ 2820 YY的GCD 莫比乌斯反演
2820: YY的GCD
Description
Input
Output
Sample Input
10 10
100 100
Sample Output
2791
HINT
T = 10000
N, M <= 10000000
思路:
题目中描述的式子即为:
$\sum\limits_{p}is[p]\sum\limits_{i=1}^{N}\sum\limits_{j=1}^{M}[gcd(i,j)=p]$
把$p$除到前面可以化简得 :
$\sum\limits_{p}is[p]\sum\limits_{i=1}^{\lfloor\frac {N}{p}\rfloor}\sum\limits_{j=1}^{\lfloor\frac {M}{p}\rfloor}[gcd(i,j)=1]$
出现$[gcd(i,j)=1]$的形式,考虑莫比乌斯反演,化简得:
$\sum\limits_{p}is[p]\sum\limits_{i=1}^{\lfloor\frac {N}{p}\rfloor}\sum\limits_{j=1}^{\lfloor\frac {M}{p}\rfloor}\sum\limits_{d|gcd(i,j)}\mu(d)$
把d提到前面得
$\sum\limits_{p}is[p]\sum\limits_{d=1}^{\lfloor\frac {\min(N,M)}{p}\rfloor}\mu(d)\sum\limits_{i=1}^{\lfloor\frac {N}{dp}\rfloor}\sum\limits_{j=1}^{\lfloor\frac {M}{dp}\rfloor}$
设$Q = dp$ 枚举$Q$化简为
$\sum\limits_{Q=1}^{\min(N,M)}\lfloor\frac{N}{Q}\rfloor \lfloor\frac{M}{Q}\rfloor\sum\limits_{p|Q}is[p]\mu(\frac{Q}{p})$
设函数$f(n) = \sum\limits_{p|n}is[p]\mu(\frac{n}{p})$
考虑得出$f(n)$
有以下几种情况 :
1. 若 $f(n)$ 为质数
值即为$\mu(1) = 1$
2. 若 $n % p == 0$ 则$f(n \times p)$可以化成$\sum\limits_{d|n\times p}is[d]\mu(\frac{n\times p}{d})$
考虑当$d!=p$时$\frac{n\times p}{d}$有多个$p$
对$\sum$的贡献为0,所以此时$f(n\times p)=\mu(n)$
1. 若 $n % p != 0$ , $f(n\times p)$可以化为$f(n)\times \mu(p) + f(p)\times \mu(n)$ 。我们又知道$\mu(p) = -1$,$f(p) = 1$,所以$f(n \times p)=\mu(n)-f(n)$
我们再处理一下前缀和, 老套路分$\sqrt n$块计算。得到结果
```cpp
#include <cstdio> #include <iostream> #include <cstring> #include <algorithm> using namespace std; const int N = 11000000; bool np[N+10]; int mu[N+10], tot, pr[N+10], sum[N+10]; int f[N+10]; int t, n, m; void init() { mu[1]=1; for(int i=2;i<=N;i++) { if(!np[i]) { pr[++tot]=i; mu[i]=-1; f[i]=1; } for(int j=1;j<=tot&&i*pr[j]<=N;j++) { np[i*pr[j]]=1; if(!(i%pr[j])) { mu[i*pr[j]]=0; f[i*pr[j]]=mu[i]; break; } mu[i*pr[j]]=-mu[i]; f[i*pr[j]]=mu[i]-f[i]; } sum[i]=sum[i-1]+f[i]; } } void solve(int n, int m) { if(n>m)swap(n,m); int lst; long long ans=0; for(int i=1;i<=n;i=lst+1) { lst = min(n/(n/i), m/(m/i)); ans+=1ll*(sum[lst]-sum[i-1])*(n/i)*(m/i); } printf("%lld\n", ans); } int main() { init(); scanf("%d",&t); while(t--) { scanf("%d%d",&n,&m); solve(n,m); } }
BZOJ 2818 双倍经验
```