P3327 [SDOI2015]约数个数和

2022-09-19 08:28:03 浏览数 (2)

Description

题目链接:P3327

d(x) 表示 x 的约数个数,有 T 组数据,给定 n,m

sumlimits_{i=1}^nsumlimits_{j=1}^md(ij)

1leq T,n,mleq 5times 10^4

Solution

首先你得知道:

d(ij)=sumlimits_{xi}sumlimits_{yj}[gcd(x,y)=1]

然后就是基本套路时间了:

sumlimits_{i=1}^nsumlimits_{j=1}^md(ij)
=sumlimits_{i=1}^nsumlimits_{j=1}^msumlimits_{xi}sumlimits_{yj}[gcd(x,y)=1]

然后套路地改为枚举 x,y

=sumlimits_{x=1}^nsumlimits_{y=1}^m[gcd(x,y)=1]sumlimits_{i=1}^nsumlimits_{j=1}^m[xi][yj]

显而易见:

=sumlimits_{x=1}^nsumlimits_{y=1}^m[gcd(x,y)=1]lfloorfrac{n}{x} rfloorlfloor frac{m}{y} rfloor

然后为了美观,把 x,y 换为 i,j,由莫比乌斯函数性质可得:

=sumlimits_{i=1}^nsumlimits_{j=1}^msumlimits_{dgcd(i,j)}mu(d)times lfloor frac{n}{i} rfloortimes lfloor frac{m}{j} rfloor

再根据常见套路,改为枚举 d

=sumlimits_{d=1}^nmu(d)sumlimits_{i=1}^{lfloor frac{n}{d} rfloor}sumlimits_{j=1}^{lfloorfrac{m}{d} rfloor}lfloor frac{n}{id}rfloor lfloor frac{m}{jd}rfloor

然后根据分配律,可以把后面式子分为两部分计算:

=sumlimits_{d=1}^nmu(d)(sumlimits_{i=1}^{lfloor frac{n}{d} rfloor}lfloor frac{n}{id}rfloor)(sumlimits_{j=1}^{lfloorfrac{m}{d} rfloor} lfloor frac{m}{jd}rfloor)

所以我们只需要预处理出 F(x)=sumlimits_{i=1}^xlfloor frac{x}{i} rfloor 即可。

=sumlimits_{d=1}^nmu(d)times F(lfloorfrac{n}{d}rfloor)times F(lfloor frac{m}{d}rfloor)

时间复杂度:mathcal O(Tsqrt N Nsqrt N)

Code

代码语言:javascript复制
#include<bits/stdc  .h>
#define Tp template<typename Ty>
#define Ts template<typename Ty,typename... Ar>
#define W while
#define I inline
#define RI register int
#define LL long long
#define Cn const
#define CI Cn int&
#define gc getchar
#define D isdigit(c=gc())
#define pc(c) putchar((c))
#define min(x,y) ((x)<(y)?(x):(y))
#define max(x,y) ((x)>(y)?(x):(y))
using namespace std;
namespace Debug{
    Tp I void _debug(Cn char* f,Ty t){cerr<<f<<'='<<t<<endl;}
    Ts I void _debug(Cn char* f,Ty x,Ar... y){W(*f!=',') cerr<<*f  ;cerr<<'='<<x<<",";_debug(f 1,y...);}
    Tp ostream& operator<<(ostream& os,Cn vector<Ty>& V){os<<"[";for(Cn auto& vv:V) os<<vv<<",";os<<"]";return os;}
    #define gdb(...) _debug(#__VA_ARGS__,__VA_ARGS__)
}using namespace Debug;
namespace FastIO{
    Tp I void read(Ty& x){char c;int f=1;x=0;W(!D) f=c^'-'?1:-1;W(x=(x<<3) (x<<1) (c&15),D);x*=f;}
    Ts I void read(Ty& x,Ar&... y){read(x),read(y...);}
    Tp I void write(Ty x){x<0&&(pc('-'),x=-x,0),x<10?(pc(x '0'),0):(write(x/10),pc(x '0'),0);}
    Tp I void writeln(Cn Ty& x){write(x),pc('n');}
}using namespace FastIO;
Cn int N=5e4 10;
int T,n,m,p[N],v[N],mu[N],tot;
LL F[N];
I void GM(){
    RI i,j,k;for(mu[1]=1,i=2;i<N;i  ) for(!v[i]&&(mu[p[  tot]=i]=-1,0),j=1;j<=tot&&i*p[j]<N;j  )
    if(v[i*p[j]]=1,i%p[j]) mu[i*p[j]]=-mu[i];else break ;
    for(i=1;i<N;i  ) mu[i] =mu[i-1];
    for(k=1;k<N;k  ) for(i=1;i<=k;i=j 1) j=k/(k/i),F[k] =1LL*(j-i 1)*(k/i);
}
I LL S(CI n,CI m){
    RI i,j;LL X=0;for(i=1;i<=min(n,m);i=j 1) j=min(n/(n/i),m/(m/i)),X =1LL*(mu[j]-mu[i-1])*F[n/i]*F[m/i];return X;
}
int main(){
    GM(),read(T);W(T--) read(n,m),writeln(S(n,m));return 0;
}

0 人点赞