hdu 5382 GCD?LCM! - 莫比乌斯反演

时间:2024-10-27 09:33:38

题目传送门

  传送门I

  传送门II

题目大意

  设$F(n) = \sum_{i = 1}^{n}\sum_{j = 1}^{n}\left [ [i, j] + (i, j) \geqslant n \right ]$,求$\sum_{i = 1}^{n} F(i)$。

  考虑设$f(n) = \sum_{i = 1}^{n}\sum_{i = 1}^{n}\left[ \left[i,j \right ] + (i, j) = n \right ]$,那么有$F(n) = F(n - 1) - f(n - 1) + 2n - 1$。(因为$[i, n]\geqslant n$)

  显然$[i, j] = k(i, j)$,那么我们可以枚举最大公约数。

  $f(n)=\sum_{d \mid n}\sum_{i = 1}^{n}\sum_{j = 1}^{n}[(i, j) = 1][[id, jd] +d = n]\\=\sum_{d \mid n}\sum_{i = 1}^{n}\sum_{j = 1}^{n}[(i, j) = 1][ijd +d = n]\\=\sum_{d\mid n}\sum_{id | (n - d)}[(i, \frac{n - d}{di}) = 1]$

  然后就是套路了。

  $f(n)=\sum_{d\mid n}\sum_{id | (n - d)}[(i, \frac{n - d}{di}) = 1]\\=\sum_{d|n}\sum_{id|(n-d)}\sum_{e|i \wedge edi\mid (n - d)}\mu(e)\\=\sum_{d|n}\sum_{de|(n - d)}\mu(e)\left( \sum_{e|i\wedge ide\mid(n - d)}1\right )\\=\sum_{d|n}\sum_{e^2d|(n - d)}\mu(e)\sigma_0\left(\frac{n-d}{e^2d}\right)$

  设$g(n) = \sum_{e^2|n}\mu(e)\sigma_0(\frac{n}{e^2})$,显然$g(n)$是可以$O(n\log n)$预处理的。考虑$i$在$1, 2,\cdots, n$中作为$\left \lfloor \frac{n}{i} \right \rfloor$个数的因子,然后枚举的总的因子的个数就是一个调和级数的和。对于$f(n)$也可以这样处理。然后就过了。

Code

 /**
* hdu
* Problem#5382
* Accepted
* Time: 655ms
* Memory: 33992k
*/
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <ctime>
using namespace std;
typedef bool boolean; const int N = 1e6 + , M = ; int add(int a, int b) {
a += b;
if (a < )
a += M;
if (a >= M)
a -= M;
return a;
} int T, n;
int f[N], F[N], S[N];
int sl[N], mp[N], mu[N];
int rou[N], g[N];
boolean vis[N];
int num, pri[]; int tp;
int fac[]; void dfs(int x, int d) {
if (x == ) {
fac[tp++] = d;
return;
}
int p = mp[x], link = sl[x];
dfs(sl[x], d);
while (!(x % p))
x /= p, d *= p, dfs(link, d);
} void dfs1(int x, int d) {
if (x == ) {
fac[tp++] = d;
return;
}
int p = mp[x], a = ;
while (!(x % p))
x /= p, a++;
a = a >> ;
for (int i = , pro = ; i <= a; i++, pro = pro * p)
dfs1(x, pro * d);
} inline void prepare() {
mu[] = , rou[] = ;
for (int i = ; i < N; i++) {
if (!vis[i])
pri[num++] = mp[i] = i, mu[i] = -, rou[i] = , sl[i] = ;
for (int j = , x; j < num && pri[j] * i < N; j++) {
x = pri[j] * i, vis[x] = true;
if (i % pri[j])
mu[x] = -mu[i], mp[x] = pri[j], sl[x] = i, rou[x] = rou[i] << ;
else {
mu[x] = , mp[x] = pri[j], sl[x] = sl[i], rou[x] = rou[x / pri[j]] + rou[sl[x]];
break;
}
}
} g[] = ;
for (int i = ; i < N; i++) {
tp = , dfs1(i, );
for (int j = , x, d; j < tp; j++) {
x = fac[j];
d = i / x / x;
if (d * x * x == i)
g[i] = add(g[i], mu[x] * rou[i / x / x]);
}
} f[] = ;
int cnt = ;
for (int i = ; i < N; i++) {
tp = , dfs(i, );
cnt += tp;
for (int j = , x; j < tp; j++) {
x = fac[j];
f[i] = add(f[i], g[(i - x) / x]);
}
} F[] = ;
for (int i = ; i < N; i++)
F[i] = add(add(F[i - ], -f[i - ]), * i - );
S[] = ;
for (int i = ; i < N; i++)
S[i] = add(S[i - ], F[i]);
} inline void solve() {
scanf("%d", &n);
printf("%d\n", S[n]);
} int main() {
prepare();
scanf("%d", &T);
while (T--)
solve();
return ;
}