您的位置:首页 > 大数据 > 人工智能

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

2016-07-29 13:32 399 查看
题目链接:

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐