http://acm.hdu.edu.cn/showproblem.php?pid=5768
求区间内,被7整除,并且模pi之后余数不为ai的个数
容斥,二进制枚举pi的情况,然后每次都把整除7放进去,根据枚举位数,加或者减。
注意解同余方程的时候,会爆longlong,所以要用快速乘。
代码:
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <cstdio>
#include <cctype>
#include <cstring>
#include <sstream>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#pragma comment(linker,"/STACK:102400000,102400000")
using namespace std;
#define MAX 100005
#define MAXN 1000005
#define maxnode 205
#define sigma_size 26
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define lrt rt<<1
#define rrt rt<<1|1
#define middle int m=(r+l)>>1
#define LL long long
#define ull unsigned long long
#define mem(x,v) memset(x,v,sizeof(x))
#define lowbit(x) (x&-x)
#define pii pair<int,int>
#define bits(a) __builtin_popcount(a)
#define mk make_pair
#define limit 10000
//const int prime = 999983;
const int INF = 0x3f3f3f3f;
const LL INFF = 0x3f3f;
const double pi = acos(-1.0);
const double inf = 1e18;
const double eps = 1e-4;
const LL mod = 1e9+7;
const ull mx = 133333331;
/*****************************************************/
inline void RI(int &x) {
char c;
while((c=getchar())<'0' || c>'9');
x=c-'0';
while((c=getchar())>='0' && c<='9') x=(x<<3)+(x<<1)+c-'0';
}
/*****************************************************/
vector<int> aa,bb;
vector<int> a,b;
LL mul(LL a,LL b,LL mod){
LL n = 0;
while(b){
if(b&1)
n = (n+a)%mod;
a = (a*2)%mod;
b /= 2;
}
return n;
}
void exgcd(LL a,LL b,LL &d,LL &x,LL &y){
if(!b){x=1;y=0;d=a;return;}
else {exgcd(b,a%b,d,y,x);y-=a/b*x;}
}
LL labs(LL a){
if(a<0) return -a;
return a;
}
LL solve(){ //x=b[i](mod a[i])
LL ta=a[0],tb=b[0];
int flag=1;
for(int i=1;i<a.size();i++){
LL xa=ta,xb=a[i],c=b[i]-tb,d,x,y;
exgcd(xa,xb,d,x,y);
if(c%d){
flag=0;
break;
}
LL tmp=xb/d;
LL k=1;
if(x<0) k*=-1;
if(c/d<0) k*=-1;
x=(mul(labs(x),labs(c/d),tmp)*k+tmp)%tmp;//加入了二分快速乘,需要把负数先变为正数
tb=ta*x+tb;
ta=ta/d*a[i];
}
if(!flag) return -1;
return tb;
}
int main(){
//freopen("in.txt","r",stdin);
int t,kase=0;
scanf("%d",&t);
while(t--){
int n;
LL x,y;
cin>>n>>x>>y;
aa.clear(),bb.clear();
for(int i=0;i<n;i++){
int xx,yy;
scanf("%d%d",&xx,&yy);
aa.push_back(xx);
bb.push_back(yy);
}
LL ans=0;
for(int i=0;i<(1<<n);i++){
a.clear(),b.clear();
LL tmp=1;
for(int j=0;j<n;j++){
if((i>>j)&1){
a.push_back(aa[j]);
b.push_back(bb[j]);
tmp*=aa[j];
}
}
a.push_back(7);
b.push_back(0);
tmp*=7;
LL k=solve();
if(k>y) continue;
LL a1=(y-k)/tmp;
LL a2=0;
if(k<x) a2=(x-1-k)/tmp+1;
int num=bits(i);
if(num%2) ans-=(a1-a2+1);
else ans+=(a1-a2+1);
}
kase++;
printf("Case #%d: %I64d\n",kase,ans);
}
return 0;
}