洛谷P2257 YY的GCD(BZOJ2820)

莫比乌斯反演

洛谷题目传送门
BZOJ题目传送门

和NOI2010能量采集很像。

同样设 f(x)=ni=1mj=1[(i,j)==x],F(x)=ni=1mj=1[x|(i,j)]=nxmx f ( x ) = ∑ i = 1 n ∑ j = 1 m [ ( i , j ) == x ] , F ( x ) = ∑ i = 1 n ∑ j = 1 m [ x | ( i , j ) ] = ⌊ n x ⌋ ⌊ m x ⌋

p p 为质数, n<m n < m ,则有

Ans=pf(p)=pp|dF(d)μ(dp)=pd=1npF(dp)μ(d)=pp|dnpdmpdμ(d)(5)(6)(7)(8) (5) A n s = ∑ p f ( p ) (6) = ∑ p ∑ p | d F ( d ) μ ( d p ) (7) = ∑ p ∑ d = 1 ⌊ n p ⌋ F ( d p ) μ ( d ) (8) = ∑ p ∑ p | d ⌊ n p d ⌋ ⌊ m p d ⌋ μ ( d )

T=dp T = d p ,则
Ans=T=1nnTmTp|Tμ(Tp) A n s = ∑ T = 1 n ⌊ n T ⌋ ⌊ m T ⌋ ∑ p | T μ ( T p )

然后除法分块一下就好了。

代码:

#include
#include
#include
#include
#define N 10000005
#define F inline
using namespace std;
typedef long long LL;
int n,m,t,mu[N],p[N],a[N];
bool f[N]; LL ans;
F char readc(){
    static char buf[100000],*l=buf,*r=buf;
    if (l==r) r=(l=buf)+fread(buf,1,100000,stdin);
    return l==r?EOF:*l++;
}
F int _read(){
    int x=0; char ch=readc();
    while (!isdigit(ch)) ch=readc();
    while (isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),ch=readc();
    return x;
}
F void Make(){
    mu[1]=1;
    for (int i=2;iif (!f[i]) p[++p[0]]=i,mu[i]=-1;
        for (int j=1,v;j<=p[0]&&(v=i*p[j])true,mu[v]=-mu[i];
            if (!(i%p[j])){ mu[v]=0; break; }
        }
    }
    for (int i=1;ifor (int j=1;p[j]*i0];j++)
            a[i*p[j]]+=mu[i];
    for (int i=1;i1];
}
int main(){
    for (Make(),t=_read();t;t--){
        n=_read(),m=_read(),ans=0;
        if (n>m) swap(n,m);
        int r=0;
        for (int l=1;l<=n;l=r+1){
            r=min(n/(n/l),m/(m/l));
            ans+=(1ll*m/l)*(1ll*n/l)*1ll*(a[r]-a[l-1]);
        }
        printf("%lld\n",ans);
    }
    return 0;
}

你可能感兴趣的:(洛谷,BZOJ,蒟蒻zxl的Blog专栏)