# bzoj2301 莫比乌斯反演+分段优化

### 思路：

g(n)=n|df(d)f(n)=n|dμ(dn)g(d)

f(n)$f(n)$代表   gcd(x,y)=n   xy$\ \ \ gcd(x,y)=n\ \ \ 的（x，y）的对数$
g(n)gcd(x,y)%n=0  xy$g(n) 代表 gcd(x,y)\%n =0 \ \ 的（x，y）的对数$

g(n)=n|df(d)

ans=solve(b,d)solve(a,d)solve(b,c)+solve(a,c)$ans = solve(b,d) - solve(a,d) - solve(b,c) + solve(a,c)$

for(int i=1,nex;i<=a;i=nex+1)
{
nex = min(a/(a/i),b/(b/i));
res += 1LL *(mu[nex]-mu[i-1])*(a/i)*(b/i);
}

Result：Accepted    $\ \ \$Memory:1728 kb    $\ \ \$Time :10772 ms

#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int maxn=5e4+5;
bool vis[maxn];
int prime[maxn];
int mu[maxn];
int n,a,b,c,d,k,x;
ll ans;
void mobius()
{
memset(vis,0,sizeof vis);
mu[1] = 1;
int tot = 0;
for(int i=2;i<maxn;i++)
{
if( !vis[i] )
{
prime[tot++] = i;
mu[i] = -1;
}
for(int j=0;j<tot;j++)
{
if(i * prime[j] >=maxn) break;
vis[i * prime[j]] = true;
if( i % prime[j] == 0)
{
mu[i * prime[j]] = 0;
break;
}
else
mu[i * prime[j]] = -mu[i];
}
}
for(int i=2;i<maxn;i++)
mu[i]+=mu[i-1];
}
ll solve(int a,int b)
{
ll res = 0;
if(a>b)swap(a,b);
for(int i=1,nex;i<=a;i=nex+1)
{
nex = min(a/(a/i),b/(b/i));
res += 1LL *(mu[nex]-mu[i-1])*(a/i)*(b/i);
}
return res;
}
int main()
{
mobius();
int T;
cin>>T;
while(T--)
{
scanf("%d%d%d%d%d",&a,&b,&c,&d,&k);
a--;
c--;
n = min(b,d);
ans = solve(b/k,d/k)+solve(a/k,c/k)-solve(a/k,d/k)-solve(c/k,b/k);
printf("%lld\n",ans);
}
return 0;
}



©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客