码迷,mamicode.com
首页 > 其他好文 > 详细

[SCOI2010]幸运数字

时间:2019-02-11 19:48:33      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:cpp   inline   span   ace   数字   include   +=   防止   其他   

Description:

求L~R内所有由6、8组成的所有数及其倍数

Hint:

\(L、R<=1e11\)

solution:

首先找出所有6、8组成的数,
其次筛掉其中是其他数倍数的数,方便容斥,
最后枚举集合统计答案
由于数据范围较大,需要几个剪枝

#include<bits/stdc++.h>
using namespace std;
const int mxn=1e6+5;
typedef long long ll;
int cnt;
ll p[mxn],b[mxn],vis[mxn],tot,l,r,ans;

int cmp(ll x,ll y) {return x>y;}
ll Gcd(ll x,ll y) {
    return y==0?y:Gcd(y,x%y);
}

void dfs(ll x)
{
    if(x>r) return ;
    if(x)
        p[++cnt]=x;
    dfs(x*10+6);
    dfs(x*10+8);
}

void init()
{
    sort(p+1,p+cnt+1);
    for(int i=1;i<=cnt;++i) {
        for(int j=1;j<i;++j) {
            if(p[i]%p[j]==0) vis[i]=1; //筛
        }
    }
    for(int i=1;i<=cnt;++i) 
        if(!vis[i]) b[++tot]=p[i];
    sort(b+1,b+tot+1,cmp);  
}

void solve(int now,int s,ll lcm)
{
    if(now==tot+1) {
        if(s==0) return ;
        ans+=(r/lcm-(l-1)/lcm)*((s&1)?1:-1); //容斥,统计答案
        return ;
    }
    solve(now+1,s,lcm);
    ll gcd=__gcd(lcm,b[now]),tp=lcm/gcd;
    if(1ll*b[now]*tp<=r&&1ll*b[now]*tp>0/*这里是防止爆ll*/) solve(now+1,s+1,tp*b[now]); //剪枝 >R就不用算了
}

int main()
{
    cin>>l>>r;
    dfs(0);
    init();
    solve(1,0,1);
    printf("%lld",ans);
    return 0;
}

[SCOI2010]幸运数字

标签:cpp   inline   span   ace   数字   include   +=   防止   其他   

原文地址:https://www.cnblogs.com/list1/p/10362894.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!