题目大意
有一个长度为 n n n的正整数序列 a i a_i ai,序列中的元素两两不同。你可以从序列中任取不同的三个元素组成一个三元组,当三元组中最大的数和最小的数两者互质,则这个三元组为合法的三元组,求这个序列中的元素组成的三元组中有多少个三元组为合法的三元组?
题解
首先我们可以将 a a a数组排序。
设 f i f_i fi表示第 i i i个元素和在第 i i i个元素之前的元素作为最大值和最小值的合法三元组的个数,则有
f i = ∑ j = 1 i ( i − j − 1 ) × [ gcd ( a i , a j ) = = 1 ] f_i=\sum\limits_{j=1}^i(i-j-1)\times [\gcd(a_i,a_j)==1] fi=j=1∑i(i−j−1)×[gcd(ai,aj)==1]
那么答案即为
∑ i = 1 n f i = ∑ i = 1 n ∑ j = 1 i ( i − j − 1 ) × [ gcd ( a i , a j ) = = 1 ] \sum\limits_{i=1}^n f_i=\sum\limits_{i=1}^n\sum\limits_{j=1}^i(i-j-1)\times [\gcd(a_i,a_j)==1] i=1∑nfi=i=1∑nj=1∑i(i−j−1)×[gcd(ai,aj)==1]
根据莫比乌斯函数的性质,原式变为
∑ i = 1 n ∑ j = 1 i ( i − j − 1 ) × ∑ k ∣ a i , k ∣ a j μ ( k ) \sum\limits_{i=1}^n\sum\limits_{j=1}^i(i-j-1)\times\sum\limits_{k|a_i,k|a_j}\mu(k) i=1∑nj=1∑i(i−j−1)×k∣ai,k∣aj∑μ(k)
先枚举 k k k得
∑ k = 1 a n μ ( k ) ∑ k ∣ a i ∑ k ∣ a j , j < i ( i − j − 1 ) \sum\limits_{k=1}^{a_n}\mu(k)\sum\limits_{k|a_i}\sum\limits_{k|a_j,j<i}(i-j-1) k=1∑anμ(k)k∣ai∑k∣aj,j<i∑(i−j−1)
用桶来存 a a a数组,枚举 k k k,然后枚举 k k k的倍数,后面的式子就可以由前缀和求出。
令 m x mx mx表示 a a a的最大值,总共枚举的次数为 m x + m x 2 + m x 3 + ⋯ + m x m x ≈ m x ln m x mx+\dfrac{mx}{2}+\dfrac{mx}{3}+\cdots+\dfrac{mx}{mx}\approx mx\ln mx mx+2mx+3mx+⋯+mxmx≈mxlnmx,所以时间复杂度为 O ( m x ln m x ) O(mx\ln mx) O(mxlnmx)。
code
#include<bits/stdc++.h>
using namespace std;
const int N=300000;
int n,a[300005],v[300005],z[300005],p[300005],mu[300005];
long long sum,tmp,w,ans=0;
void init(){
mu[1]=1;
for(int i=2;i<=N;i++){
if(!z[i]){
p[++p[0]]=i;
mu[i]=-1;
}
for(int j=1;j<=p[0]&&i*p[j]<=N;j++){
z[i*p[j]]=1;
if(i%p[j]==0) break;
mu[i*p[j]]=-mu[i];
}
}
}
int main()
{
init();
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
sort(a+1,a+n+1);
for(int i=1;i<=n;i++){
v[a[i]]=i;
}
for(int i=1;i<=a[n];i++){
sum=tmp=w=0;
for(int j=i;j<=a[n];j+=i){
if(!v[j]) continue;
sum+=(v[j]-1)*w-tmp;
++w;tmp+=v[j];
}
ans+=mu[i]*sum;
}
printf("%lld",ans);
return 0;
}