/*
题目描述:给出n(0<=n<=15)对pi , ai ( 0 < ai < pi , 且p1*p2*...*pn < 1e18),问在x到y(0 < x < y < 1e18)的范围内有多少
数字是7的倍数,且对任意pi取余的结果不为ai
思路:初始另ans等于x到y之间7的倍数的个数通过容斥原理的角度思考,将条件写成式子
x = 0 (mod 7)
x = a1 (mod p1)
...
x = an (mod pn)
在第一个式子一定存在的前提下,剩下的每个式子可以有或没有,用取出来的式子组成一个方程组,根据中国剩余定理解出
所有在x到y之间的解的个数ccnt,如果方程组中方程的个数为奇,那么ans += ccnt , 如果方程个数为偶,那么ans -= ccnt
最终ans即为答案
*/
#pragma warning(disable:4786)
#pragma comment(linker, "/STACK:102400000,102400000")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<vector>
#include<cmath>
#include<string>
#include<sstream>
#include<bitset>
#define LL long long
#define FOR(i,f_start,f_end) for(int i=f_start;i<=f_end;++i)
#define mem(a,x) memset(a,x,sizeof(a))
#define lson l,m,x<<1
#define rson m+1,r,x<<1|1
using namespace std;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const double PI = acos(-1.0);
const double eps=1e-6;
LL p[30] , a[30];
LL x , y , ans;
int n;
bool flag;
struct node
{
LL p , a;
bool operator < (const node & rhs)const
{
if(p < rhs.p) return true;
else if(p == rhs.p) return a < rhs.a;
else return false;
}
};
vector<node>v;
LL ex_gcd(LL a , LL b , LL & x , LL & y)
{
if(b == 0){
x = 1 ; y = 0;
return a;
}
else{
LL d = ex_gcd(b , a % b , y , x);
y = y - a / b * x;
return d;
}
}
LL bsearch(LL left , LL right , LL base , LL add , LL val)
{
LL ret = -INF , mid;
while(left <= right){
mid = left + (right - left) / 2;
if(base + mid * add <= val){
ret = mid;
left = mid + 1;
}
else{
right = mid - 1;
}
}
return ret;
}
LL solve() //根据中国剩余定理求出解的个数
{
LL a1 , a2 , r1 , r2 , x0 , y0;
bool ok = 1;
int sz = v.size();
if(sz == 1)
return 0;
a1 = v[0].p;
r1 = v[0].a;
for(int i = 1 ; i < sz ; i++){
a2 = v[i].p;
r2 = v[i].a;
LL d = ex_gcd(a1 , a2 , x0 , y0);
LL c = r2 - r1 ;
if(c % d){
ok = 0;
break;
}
LL m = a2 / d;
x0 = (x0 * c / d % m + m) % m;
r1 = a1 * x0 + r1;
a1 = a1 * (a2 / d);
}
if(!ok){
flag = 0;
return flag;
}
LL ans1 = bsearch(0 , x / a1 + 1, r1 , a1 , x) + 1LL;
if(r1 + ans1 * a1 - a1 == x)
--ans1;
LL ans2 = bsearch(0 , y / a1 + 1, r1 , a1 , y) + 1LL;
if(ans1 < 0) ans1 = 0;
if(ans2 < 0) ans2 = 0;
return (ans2 - ans1 );
}
void dfs(int cnt , int st) //容斥原理可以利用深搜实现
{
if(cnt == n){
int siz = v.size();
LL add = solve();
if(st % 2){
ans -= add;
}
else{
ans += add;
}
return ;
}
node cur = {p[cnt + 1] , a[cnt + 1]};
v.push_back(cur);
dfs(cnt + 1 , st + 1);
v.pop_back();
dfs(cnt + 1 , st);
}
int main()
{
int T , kase = 0;
scanf("%d",&T);
node st = {7LL , 0LL};
while(T--){
v.clear();
v.push_back(st);
flag = 1;
scanf("%d %lld %lld", &n , &x , &y);
for(int i = 1 ; i <= n; i++){
scanf("%lld %lld",&p[i] , &a[i]);
}
ans = y /7LL - x / 7LL;
if(!(x % 7)) ++ans;
LL res = ans;
dfs(0 , 0);
if(!flag){
printf("Case #%d: %lld\n",++kase , res);
}
else{
printf("Case #%d: %lld\n",++kase , ans);
}
}
return 0;
}
hdu5768 Lucky7 中国剩余定理 + 容斥原理
最新推荐文章于 2018-10-20 15:40:40 发布