HDU 5768 Lucky7

题目链接:http://acm.split.hdu.edu.cn/showproblem.php?pid=5768


题意:给出n对(p,a),求区间[L,R]内为7的倍数,且不满足任意i∈n, x % pi = ai的个数。


思路:容斥定理,设单独事件Ai为区间内为7的倍数且满足x % pi = ai的个数。那么区间内7的倍数的个数 - A1∪A2∪A3...∪Ai即为答案。然后计算过程中需要借助中国剩余定理计算出最小满足条件的数从而得到满足当前条件的数的个数。


#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <utility>
using namespace std;

#define rep(i,j,k) for (int i=j;i<=k;i++)
#define Rrep(i,j,k) for (int i=j;i>=k;i--)

#define Clean(x,y) memset(x,y,sizeof(x))
#define LL long long
#define ULL unsigned long long
#define inf 0x7fffffff
#define mod 100000007
const int maxn = 20;

int n;
LL L,R;
LL prime[maxn],ret[maxn];

LL exgcd( LL a , LL b , LL &x , LL &y )
{
    if ( b == 0 )
    {
        x = 1 , y = 0;
        return a;
    }
    LL r = exgcd( b , a % b , y , x );
    y -= x * ( a / b );
    return r;
}

LL gcd( LL a , LL b )
{
    return b==0?a:gcd(b,a%b);
}

// X 同余 a[i] ( mod m[i] )  ,有n个式子(ai,mi),求X
LL CRT( LL a[] , LL m[] , int n )
{
    LL M = m[0];
    LL R = a[0];
    rep(i,1,n)
    {
        LL d = gcd(M,m[i]);
        LL c = a[i] - R;
        if ( c % d ) return -1; //无解
        LL x,y;
        exgcd(M/d,m[i]/d,x,y);
        x = ( c / d * x )%(m[i]/d);
        R = R + x * M;
        M = M / d * m[i];
        R %= M;
    }
    if ( R < 0 ) R += M;
    return R;
}

LL cal( LL N )
{
    if ( N == 0 ) return 0;
    LL p[maxn] , a[maxn];
    LL ans = N/7;
    int uplim = (1<<n)-1;
    p[0] = 7 , a[0] = 0;
    rep(i,1,uplim)
    {
        int num = 0;
        LL sum = 7;
        rep(j,1,n)
            if( i & 1<<(j-1) ) sum *= prime[j] , num++ , p[num] = prime[j] , a[num] = ret[j];
        LL st = CRT( a , p , num ); //最小满足条件的数
        if ( st == -1 ) continue;
        int first = st <= N;//首个数是否在范围内
        if ( num & 1 ) ans -= max( 0LL ,  (N - st) ) / sum + first;
        else ans += max( 0LL ,  (N - st) ) / sum + first;
    }
    return ans;
}

void init()
{
    scanf("%d %I64d %I64d",&n,&L,&R);
    prime[0] = 7 , ret[0] = 0;
    rep(i,1,n) scanf("%I64d%I64d",&prime[i],&ret[i]);
}

int main()
{
    int T;
    cin>>T;
    rep(cas,1,T)
    {
        printf("Case #%d: ",cas);
        init();
        printf("%I64d\n", cal(R) - cal(L-1) );
    }
    return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值