BZOJ 3994 [SDOI2015]约数个数和

题目链接

https://lydsy.com/JudgeOnline/problem.php?id=3994

题解

莫比乌斯反演得到
∑ k = 1 n μ ( k ) ∑ i = 1 ⌊ n / k ⌋ σ 0 ( i ) ∑ i = 1 ⌊ n / k ⌋ σ 0 ( i ) \sum_{k=1}^{n} \mu(k)\sum_{i=1}^{\lfloor n/k\rfloor}\sigma_0(i)\sum_{i=1}^{\lfloor n/k\rfloor}\sigma_0(i) k=1nμ(k)i=1n/kσ0(i)i=1n/kσ0(i)
预处理出 σ 0 \sigma_0 σ0的前缀和,整除分块即可。

代码

#include 
#include 

int read()
{
  int x=0,f=1;
  char ch=getchar();
  while((ch<'0')||(ch>'9'))
    {
      if(ch=='-')
        {
          f=-f;
        }
      ch=getchar();
    }
  while((ch>='0')&&(ch<='9'))
    {
      x=x*10+ch-'0';
      ch=getchar();
    }
  return x*f;
}

const int maxn=50000;

int p[maxn+10],prime[maxn+10],cnt,mu[maxn+10],low[maxn+10],num[maxn+10],d[maxn+10];

int getprime()
{
  p[1]=mu[1]=d[1]=num[1]=1;
  low[1]=0;
  for(int i=2; i<=maxn; ++i)
    {
      if(!p[i])
        {
          prime[++cnt]=i;
          mu[i]=-1;
          low[i]=1;
          num[i]=1;
          d[i]=2;
        }
      for(int j=1; (j<=cnt)&&(i*prime[j]<=maxn); ++j)
        {
          int x=i*prime[j];
          p[x]=1;
          if(i%prime[j]==0)
            {
              mu[x]=0;
              low[x]=low[i]+1;
              num[x]=num[i];
              d[x]=d[num[x]]*(low[x]+1);
              break;
            }
          mu[x]=-mu[i];
          low[x]=1;
          num[x]=i;
          d[x]=d[i]*2;
        }
    }
  for(int i=1; i<=maxn; ++i)
    {
      d[i]+=d[i-1];
    }
  for(int i=1; i<=maxn; ++i)
    {
      mu[i]+=mu[i-1];
    }
  return 0;
}

int T,n,m;

int main()
{
  getprime();
  T=read();
  while(T--)
    {
      n=read();
      m=read();
      long long ans=0;
      for(int l=1,r; l<=std::min(n,m); l=r+1)
        {
          r=std::min(n/(n/l),m/(m/l));
          ans+=1ll*(mu[r]-mu[l-1])*d[n/l]*d[m/l];
        }
      printf("%lld\n",ans);
    }
  return 0;
}

你可能感兴趣的:(莫比乌斯反演)