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




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