[bzoj2301]Problem b莫比乌斯反演+分块优化

时间:2023-05-19 12:02:44

题意:

$\sum\limits_{\begin{array}{*{20}{c}}
{a < = x < = b}\\
{c < = y < = d}
\end{array}} {\gcd (x,y) = = k} $

解题关键:

现令$f(i)$表示有多少对${(x,y)}$满足 ${\gcd (x,y) =  = d}$,$1 <  = x <  = n,1 <  = y <  = m$

$F(d)$为有多少对${(x,y)}$满足 ${\gcd (x,y) =  = d}$的倍数

$f(d) = \sum\limits_{\begin{array}{*{20}{c}}
{1 < = x < = n}\\
{1 < = y < = m}
\end{array}} {\gcd (x,y) = = d} $

$\begin{array}{l}
F(d) = \frac{n}{d} * \frac{m}{d}\\
\begin{array}{*{20}{l}}
{F(d) = \sum\limits_{d|x} {f(x)} \Rightarrow }\\
{f(d) = \sum\limits_{d|x} {u(\frac{x}{d})F(x)} = \sum\limits_{d|x} {u(\frac{x}{d})\left\lfloor {\frac{n}{x}} \right\rfloor } \left\lfloor {\frac{m}{x}} \right\rfloor }
\end{array}\\
= \sum\limits_{d|x}^{\min (n,m)} {u(\frac{x}{d})} \left\lfloor {\frac{n}{x}} \right\rfloor \left\lfloor {\frac{m}{x}} \right\rfloor
\end{array}$

再根据二维前缀和的型,$ans = g(b,d,k) + g(a - 1,c - 1,k) - g(a - 1,d,k) - g(b,c - 1,k)$

法二:稍微转化一下。

$\begin{array}{*{20}{l}}
{f(d) = {\sum _{\begin{array}{*{20}{c}}
{1 < = x < = n}\\
{1 < = y < = m}
\end{array}}}\gcd (x,y) = = d}\\
{ = {\sum _{\begin{array}{*{20}{c}}
{1 < = x < = n}\\
{1 < = y < = m}
\end{array}}}\gcd (\frac{x}{d},\frac{y}{d}) = = 1}\\
{\begin{array}{*{20}{l}}
{ = {\sum _{\begin{array}{*{20}{c}}
{1 < = x < = \frac{n}{d}}\\
{1 < = y < = \frac{m}{d}}
\end{array}}}\gcd (x,y) = = 1}\\
{ = \sum\limits_{i = 1}^{\min (\frac{n}{d},\frac{m}{d})} u (i)F(i)}
\end{array}}\\
{ = \sum\limits_{i = 1}^{\min (\frac{n}{d},\frac{m}{d})} u (i)\left\lfloor {\frac{n}{{di}}} \right\rfloor \left\lfloor {\frac{m}{{di}}} \right\rfloor }\\
{}
\end{array}$

预处理前缀和+分块,$n/i$这种类型的一般要考虑重复性,利用分块可以优化到根号的复杂度。

观察式子,会发现$\left\lfloor {\frac{n}{d}} \right\rfloor $最多有$2\sqrt n $个取值,同理,$\left\lfloor {\frac{m}{d}} \right\rfloor $最多有$2\sqrt m $个取值,枚举这$2(\sqrt n  + \sqrt m )$个取值,对莫比乌斯函数维护一个前缀和,可以在$O(\sqrt n )$内求出解。

n/(n/i)就是满足商为n/i的i的最大值

复杂度的详细证明:http://blog.csdn.net/outer_form/article/details/50590197

 #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
//莫比乌斯函数线性筛法
const int maxn=+;
bool vis[maxn];
int prime[maxn],mu[maxn],sum1[maxn];
void init_mu(int n){
int cnt=;
mu[]=;
for(int i=;i<n;i++){
if(!vis[i]){
prime[cnt++]=i;
mu[i]=-;
}
for(int j=;j<cnt&&i*prime[j]<n;j++){
vis[i*prime[j]]=;
if(i%prime[j]==) {mu[i*prime[j]]=;break;}
else { mu[i*prime[j]]=-mu[i];}
}
}
for(int i=;i<n;i++){
sum1[i]=sum1[i-]+mu[i];
}
}
inline int read(){
char k=;char ls;ls=getchar();for(;ls<''||ls>'';k=ls,ls=getchar());
int x=;for(;ls>=''&&ls<='';ls=getchar())x=(x<<)+(x<<)+ls-'';
if(k=='-')x=-x;return x;
}
int fun(int n,int m,int k){
n/=k,m/=k;
if(n>m) swap(n,m);
int ans=,pos;
for(int i=;i<=n;i=pos+){
pos=min(n/(n/i),m/(m/i));
ans+=(sum1[pos]-sum1[i-])*(n/i)*(m/i);
}
return ans;
}
int main(){
int t,a,b,c,d,k;
init_mu();
t=read();
while(t--){
a=read(),b=read(),c=read(),d=read(),k=read();
int t1=fun(b,d,k),t2=fun(a-,c-,k),t3=fun(a-,d,k),t4=fun(b,c-,k);
int ans=t1+t2-t3-t4;
printf("%d\n",ans);
}
}