P2522 [HAOI2011]Problem b

2022-09-16 14:30:26 浏览数 (2)

Description

题目链接:P2522

T 组数据,求

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

1leq T,x,y,n,m,kleq 5times 10 ^4

Solution

可以根据容斥原理,原式可以分成四个子问题,每个子问题的式子为:

sumlimits_{i=1}^nsumlimits_{j=1}^m[gcd(i,j)=k]

考虑化简:

sumlimits_{i=1}^{lfloorfrac{n}{k}rfloor}sumlimits_{j=1}^{lfloor frac{m}{k}rfloor}[gcd(i,j)=1]

根据莫比乌斯函数性质,将函数展开可以得到:

sumlimits_{i=1}^{lfloorfrac{n}{k}rfloor}sumlimits_{j=1}^{lfloor frac{m}{k}rfloor}sumlimits_{dgcd(i,j)}mu(d)

变换求和顺序,先枚举 dgcd(i,j),可以得到:

sumlimits_{d=1}mu(d)sumlimits_{i=1}^{lfloorfrac{n}{k}rfloor}[di]sumlimits_{j=1}^{lfloor frac{m}{k}rfloor}[dj]

易知 1 sim lfloorfrac{n}{k}rfloord 的倍数有 lfloor frac{n}{kd} rfloor 个,故原式化为:

sumlimits_{d=1}mu(d) lfloor frac{n}{kd} rfloorlfloorfrac{m}{kd} rfloor

然后直接用数论分块求解即可。

时间复杂度:mathcal{O}(N Tsqrt 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,a,b,c,d,k,p[N],v[N],mu[N],tot;
I void GM(){
    RI i,j;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];
}
I int S(CI n,CI m){
    RI i,j,X=0;for(i=1;i<=min(n,m);i=j 1) j=min(n/(n/i),m/(m/i)),X =(mu[j]-mu[i-1])*(n/i)*(m/i);return X;
}
int main(){
    GM(),read(T);W(T--) read(a,b,c,d,k),writeln(S(b/k,d/k)-S(b/k,(c-1)/k)-S((a-1)/k,d/k) S((a-1)/k,(c-1)/k));return 0;
}

0 人点赞