题解 CF900D 【Unusual Sequences】
Description
题目链接:Codeforces 900D
求满足下面两个条件的数列
-
\gcd(a_1,a_2,\dots,a_n)=x -
\sum_{i=1}^n a_i=y
数据范围:
Solution
如果在
我们令
我们先不考虑
对于
我们发现,
接下来介绍两种做法:
递推
我们可以考虑容斥原理:所有序列数量减去不合法的序列数量。我们枚举不合法的序列的
由于一个数的因子的因子也一定是这个数的因子,所以我们发现需要的
时间复杂度:
反演
我们发现:
这个式子的本质是
这样一来我们就可以直接暴力求解了。
时间复杂度:
Code
递推
#include <cstdio>
#include <map>
const int mod=1e9+7;
std::map<int,int> mp;
int pow(int x,int p) {
int ret=1;
for(;p;p>>=1,x=1LL*x*x%mod) if(p&1) ret=1LL*ret*x%mod;
return ret;
}
void upd(int &x,int y) {
(x+=y)>=mod&&(x-=mod);
}
int solve(int n) {
if(n==1) return 1;
if(mp.count(n)) return mp[n];
int ans=0;
for(int i=2;i*i<=n;++i) {
if(n%i==0) {
upd(ans,solve(i));
if(i*i!=n) upd(ans,solve(n/i));
}
}
upd(ans,solve(1));
ans=(pow(2,n-1)-ans+mod)%mod;
return mp[n]=ans;
}
int main() {
int x,y;
scanf("%d%d",&x,&y);
if(y%x) return puts("0"),0;
printf("%d\n",solve(y/x));
return 0;
}
反演
#include <cstdio>
const int N=1e5+5;
const int mod=1e9+7;
int x,y,tot,p[N];
bool flg[N];
void sieve(int n) {
for(int i=2;i<=n;++i) {
if(!flg[i]) p[++tot]=i;
for(int j=1;j<=tot&&i*p[j]<=n;++j) {
flg[i*p[j]]=1;
if(i%p[j]==0) break;
}
}
}
int mu(int n) {
int cnt=0;
for(int i=1;i<=tot&&1LL*p[i]*p[i]<=n;++i) {
if(n%p[i]) continue;
int now=0;
while(n%p[i]==0) n/=p[i],++now;
if(now>1) return 0;
++cnt;
}
if(n>1) ++cnt;
return cnt%2==0?1:mod-1;
}
int pow(int x,int p) {
int ret=1;
for(;p;p>>=1,x=1LL*x*x%mod) if(p&1) ret=1LL*ret*x%mod;
return ret;
}
void upd(int &x,int y) {
(x+=y)>=mod&&(x-=mod);
}
int main() {
sieve(N-5);
scanf("%d%d",&x,&y);
if(y%x) return puts("0"),0;
int n=y/x,ans=0;
for(int i=1;1LL*i*i<=n;++i) {
if(n%i==0) {
upd(ans,1LL*mu(n/i)*pow(2,i-1)%mod);
if(i*i!=n) upd(ans,1LL*mu(i)*pow(2,n/i-1)%mod);
}
}
printf("%d\n",ans);
return 0;
}