51nod1675 序列变换

时间:2023-03-09 18:00:36
51nod1675 序列变换

link

题意:

给定长为n的序列a,b,下标从1开始,问有多少对x,y满足gcd(x,y)=1且$a_{b_x}=b_{a_y}$?

$n\leq 10^5.$

题解:

$a_{b_x}$和$b_{a_y}$是个幌子,定义成$A_x$和$B_y$就好了,没有什么影响。

考虑倍数反演:记f(i)表示i=gcd(x,y)的方案数;g(i)表示i|gcd(x,y)的方案数。g(i)可以枚举倍数得到。那么有:

$$\begin{equation}g(n)=\sum_{n|d}f(d)\Longrightarrow f(n)=\sum_{n|d}\mu(\frac{d}{n})g(d)\end{equation}$$

证明

这里只需要$f(1)=\sum_{i=1}^{n}\mu(i)\times g(i)$。

复杂度$\mathcal{O}(n\log n)$。

code:

 #include<bits/stdc++.h>
#define rep(i,x,y) for (int i=(x);i<=(y);i++)
#define ll long long
#define inf 1000000001
#define y1 y1___
using namespace std;
char gc(){
static char buf[],*p1=buf,*p2=buf;
return p1==p2&&(p2=(p1=buf)+fread(buf,,,stdin),p1==p2)?EOF:*p1++;
}
#define gc getchar
ll read(){
char ch=gc();ll x=;int op=;
for (;!isdigit(ch);ch=gc()) if (ch=='-') op=-;
for (;isdigit(ch);ch=gc()) x=(x<<)+(x<<)+ch-'';
return x*op;
}
#define N 100005
int n,a[N],b[N],t[N],mu[N],p[N],cnt;ll ans,g[N];bool vis[N];
void init(int n){
mu[]=;
rep (i,,n){
if (!vis[i]) p[++cnt]=i,mu[i]=-;
for (int j=;j<=cnt&&i*p[j]<=n;j++){
vis[i*p[j]]=;
if (i%p[j]==) break;
mu[i*p[j]]=-mu[i];
}
}
}
int main(){
n=read();init(n);
rep (i,,n) a[i]=read();
rep (i,,n) b[i]=read();
rep (d,,n){
for (int i=d;i<=n;i+=d) t[b[a[i]]]++;
for (int i=d;i<=n;i+=d) g[d]+=t[a[b[i]]];
for (int i=d;i<=n;i+=d) t[b[a[i]]]--;
}
rep (i,,n) ans+=mu[i]*g[i];
printf("%lld\n",ans);
return ;
}