CRT+容斥定理——Luck7 ( HDU 5768 ) ( 2016 Multi-University Training Contest 4 1005 )

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

  • 分析:
    给出区间 [x,y] 和 数字n,再给出n行,每行为ai 与 pi,求出区间内 7 的倍数且模ai余数不为pi的数的个数。我们可以用CRT求出所有模ai余pi的数。

  • 题解:
    利用CRT和二进制状态压缩计算不满足条件的数,然后用容斥定理计算答案

  • 参考代码:


#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;

const int maxn = 20;
LL a[maxn], m[maxn];
LL N;

LL multimod(LL x,LL y,LL m)//模乘法
{
    LL ans=0;
    while(y)
    {
        if(y&1)
        {
            ans+=x;
            ans%=m;
        }
        x+=x;
        x%=m;
        y>>=1;
    }
    ans=(ans+m)%m;
    return ans;
}

void Exgcd(LL a, LL b, LL &x ,LL &y)
{
   if(!b)  {x = 1;y = 0;return; }
    Exgcd(b, a % b, x, y);
    LL tmp = x;
    x = y;
    y = tmp - (a / b) * y;
}

LL CRT ( LL num)
{
    LL totalsum=0;
    for(int i=0;i<(1<<N);i++)
    {
        LL M=7,ans=0,count=0,x=0,y;
        for(int j=0;j<N;j++)
            if(i&(1<<j))//解每种情况的方程
            {
                M*=a[j];
                count++;
            }
        for(int j=0;j<N;j++)
            if(i&(1<<j))//解每种情况的方程
            {
                LL Mi=M/a[j];
                Exgcd(Mi,a[j],x,y);
                ans=(ans+multimod(multimod(x,Mi,M), m[j],M))%M;
            }
        ans=(ans+M)%M;
        cout << ans << endl;//得到满足模ai余pi的数
         LL res=num/M+(num%M>=ans);
         cout << count << "   QAQ  " << res << endl;
        if(count%2)  totalsum-=res;//容斥原理的体现
        else totalsum+=res;
    }
    return totalsum;
}


int main()
{
    int T;
    scanf("%d", &T);
    int tt = 1;
    while(T--)
    {
        LL x,y;
        scanf("%lld%lld%lld", &N, &x, &y);
        for(int i=0;i<N;i++)
        {
            scanf("%lld%lld",&a[i],&m[i]);
        }

        printf("Case #%d: %lld\n", tt++, CRT(y)-CRT( x-1));
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值