bzoj2393 容斥原理

因爲是權限題所以把題目粘過來

2393: Cirno的完美算數教室

Time Limit: 10 Sec  Memory Limit: 128 MB
Submit: 108  Solved: 62
[Submit][Status]

Description

~Cirno發現了一種baka數,這種數呢~只含有2和⑨兩種數字~~
現在Cirno想知道~一個區間中~~有多少個數能被baka數整除~
但是Cirno這麼天才的妖精纔不屑去數啦
只能依靠聰明的你咯。
 
 

Input

一行正整數L R
( 1 < L < R < 10^10)
 

Output

一個正整數,代表所求的答案
 

Sample Input

1 100

Sample Output

58


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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章