洛谷 3911.最小公倍数之和

首先设 lim=maxi=1Nai,ck=i=1N[ai=k]lim = \max\limits_{i = 1}^N a_i,c_k = \sum\limits_{i = 1}^N [a_i = k]
于是问题转化为求解 i=1limj=1limlcm(i,j)cicj\sum\limits_{i = 1}^{lim} \sum\limits_{j = 1}^{lim} \text{lcm}(i,j) c_i c_j

f(x)=idlimjdlim[gcd(i,j)=x]ijcidcjd,F(x)=xdf(d)=idlimjdlim[xgcd(i,j)]ijcidcjdf(x) = \sum\limits_{id \le lim} \sum\limits_{jd \le lim} [\gcd(i,j) = x]ijc_{id}c_{jd},F(x) = \sum\limits_{x | d} f(d) = \sum\limits_{id \le lim} \sum\limits_{jd \le lim} [x | \gcd(i,j)]ijc_{id}c_{jd}

于是可以预处理 (xdlimjcxd)2\left(\sum\limits_{xd \le lim} jc_{xd}\right)^2 然后这题就没了。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <cstdio>
using namespace std;
const int N = 5e4;
int n,lim,c[N + 5];
int vis[N + 5],prime[N + 5],cnt,mu[N + 5];
long long f[N + 5];
long long ans;
int main()
{
mu[1] = 1;
for(register int i = 2;i <= N;++i)
{
if(!vis[i])
mu[prime[++cnt] = i] = -1;
for(register int j = 1;j <= cnt && i * prime[j] <= N;++j)
{
vis[i * prime[j]] = 1;
if(!(i % prime[j]))
break;
else
mu[i * prime[j]] = -mu[i];
}
}
scanf("%d",&n);
int x;
for(register int i = 1;i <= n;++i)
scanf("%d",&x),++c[x],lim = max(lim,x);
for(register int i = 1;i <= lim;f[i] *= f[i],++i)
for(register int j = 1;i * j <= lim;++j)
f[i] += (long long)j * c[i * j];
for(register int i = 1;i <= lim;++i)
for(register int j = 1;i * j <= lim;++j)
ans += (long long)i * j * j * mu[j] * f[i * j];
printf("%lld\n",ans);
}