题目链接:点这里!!!
这道题比赛的时候改了将近3个小时还是没有过,后来知道在求模方程的时候乘爆了,后来用快速乘就秒A了,还是太弱啦!
题意:
小明认为能被7整除的数能给他带来好运,但是如果这些数存在x%pi=ai(1<=i<=n)的话,它反而会给小明带来坏运。
问[x,y]区间里有多少个数能给小明带来好运?
数据范围:
0<=n<=15,0<x<y<1e18,0<ai<pi<1e5,p1*p2*...pn<=1e18.保证pi!=7,且pi互不相同。
题解:
我们可以利用中国剩余定理解出模方程然后利用O(1)的时间求到区间内满足条件的数有多少,再利用容斥原理得到最后的答案,这里要注意一点,求解模方程的时候会乘爆long long,我们利用快速乘就可以完美解决了!
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<sstream>
#include<algorithm>
#include<vector>
#include<bitset>
#include<set>
#include<queue>
#include<stack>
#include<map>
#include<cstdlib>
#include<cmath>
#define pb push_back
#define pa pair<int,int>
#define clr(a,b) memset(a,b,sizeof(a))
#define lson lr<<1,l,mid
#define rson lr<<1|1,mid+1,r
#define bug(x) printf("%d++++++++++++++++++++%d\n",x,x)
#define key_value ch[ch[root][1]][0]
#pragma comment(linker, "/STACK:102400000000,102400000000")
typedef long long LL;
const LL MOD = 1000000007;
const int N = 20;
const int maxn = 1e6+15;
const int letter = 130;
const int INF = 1e9+7;
const double pi=acos(-1.0);
const double eps=1e-10;
using namespace std;
inline int read()
{
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
int n;
LL x,y,p[20],a[20],u[N],v[N];
LL s[maxn],t[maxn];
void ex_gcd(LL a,LL b,LL &d,LL &x,LL &y) {
if (!b) { d=a;x=1;y=0; }
else { ex_gcd(b,a%b,d,y,x);y-=x*(a/b); }
}
LL cc(LL a,LL b,LL p){
LL ans=0,pc=a;
while(b){
if(b&1){
ans=(ans+pc)%p;
b--;
}
else {
pc=(pc*2)%p;
b=b/2;
}
}
return ans;
}
LL CRT1(int n,LL *a,LL *m) {
LL M=1,d,y,z,x=0;
for (int i=0;i<n;i++) M*=m[i];
for (int i=0;i<n;i++) {
z=M/m[i];
ex_gcd(m[i],z,d,d,y);
///x=(x+y%M*z%M*a[i]%M)%M;
x=(x+cc(cc(y,z,M),a[i],M))%M;
}
return (x+M)%M;
}
int main(){
int T,cas=0;
scanf("%d",&T);
while(T--){
cin>>n>>x>>y;
for(int i=0;i<n;i++)cin>>p[i]>>a[i];
LL sum=0;
for(int g=0;g<(1<<n);g++){
int cnt=0,vv=0;
LL pp=7;
u[cnt]=7,v[cnt++]=0;
for(int i=0;i<n;i++){
if((g&(1<<i))) u[cnt]=p[i],v[cnt++]=a[i],vv++,pp=pp*p[i];
}
LL ps=CRT1(cnt,v,u);
LL c=0,d=0;
if(x-1-ps<0) c=0;
else c=(x-1-ps)/pp+1;
if(y-ps<0) d=0;
else d=(y-ps)/pp+1;
LL ans=0;
if(c>=d) ans=0;
else ans=d-c;
if(vv&1) sum-=ans;
else sum+=ans;
}
printf("Case #%d: %I64d\n",++cas,sum);
}
return 0;
}