因爲是權限題所以把題目粘過來
2393: Cirno的完美算數教室
Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 108 Solved: 62
[Submit][Status]
Description
Input
Output
Sample Input
Sample Output
1到r中有多少個x,滿足x是y的約數,y只含2與9(範圍10^9)
本提用了容斥原理
10^9中只含2和9的質數大概只有30個不到,那麼我們只需要求出任意兩個集合的並,用容斥原理的公式即偶減去奇加上。
然後爆搜即可,加上減枝:如果兩個數的lcm大於r就continue
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<cmath>
#define MAX 2100
#define rep(i,j,k) for(int i=j;i<=k;i++)
#define ll long long
using namespace std;
int t,vis[MAX];
ll n,m,a[MAX],b[MAX],ans=0,l,r;
ll gcd(ll a1,ll a2)
{
return a2?gcd(a2,a1%a2):a1;
}
void prework(ll x,ll y)
{
if(y>r)
return;
if(x>1)
a[++m]=y;
if(x>t)
return;
prework(x+1,y*10+2);
prework(x+1,y*10+9);
}
void dfs(ll x,ll y,ll z)
{
if(x>n)
{
if(y&1)
ans+=r/z-(l-1)/z;
else
if(y)
ans-=r/z-(l-1)/z;
return;
}
dfs(x+1,y,z);
ll next=a[x]*z/gcd(a[x],z);
if(next<=r)
dfs(x+1,y+1,next);
return;
}
int main()
{
cin>>l>>r;
t=(int)(log(r*1.0)/log(10))+1;
prework(1,0);
sort(a+1,a+1+m);
rep(i,1,m)
if(!vis[i])
{
b[++n]=a[i];
rep(j,i+1,m)
if(!a[j]%a[i])
vis[j]=1;
}
rep(i,1,n)
a[n-i+1]=b[i];
dfs(1,0,1);
printf("%lld\n",ans);
return 0;
}