【中国剩余定理】【容斥原理】【快速乘法】【数论】HDU 5768 Lucky7

题目链接:

  http://acm.hdu.edu.cn/showproblem.php?pid=5768

题目大意

  T组数据,求L~R中满足:1.是7的倍数,2.对n个素数有 %pi!=ai  的数的个数。

题目思路:

  【中国剩余定理】【容斥原理】【快速乘法】【数论】

  因为都是素数所以两两互素,满足中国剩余定理的条件。

  把7加到素数中,a=0,这样就变成解n+1个同余方程的通解(最小解)。之后算L~R中有多少解。

  但是由于中国剩余定理的条件是同时成立的,而题目是或的关系,所以要用容斥原理叠加删减。

  中间过程中可能会爆long long,所以要用快速乘法(和快速幂类似,只是乘改成加)

 

  1 //
  2 //by coolxxx
  3 //
  4 #include<iostream>
  5 #include<algorithm>
  6 #include<string>
  7 #include<iomanip>
  8 #include<memory.h>
  9 #include<time.h>
 10 #include<stdio.h>
 11 #include<stdlib.h>
 12 #include<string.h>
 13 //#include<stdbool.h>
 14 #include<math.h>
 15 #define min(a,b) ((a)<(b)?(a):(b))
 16 #define max(a,b) ((a)>(b)?(a):(b))
 17 #define abs(a) ((a)>0?(a):(-(a)))
 18 #define lowbit(a) (a&(-a))
 19 #define sqr(a) ((a)*(a))
 20 #define swap(a,b) ((a)^=(b),(b)^=(a),(a)^=(b))
 21 #define eps (1e-8)
 22 #define J 10000000
 23 #define MAX 0x7f7f7f7f
 24 #define PI 3.1415926535897
 25 #define N 24
 26 using namespace std;
 27 typedef long long LL;
 28 int cas,cass;
 29 int n,m,lll;
 30 LL l,r,ans;
 31 LL p[N],a[N];
 32 bool u[N];
 33 LL cheng(LL a,LL b,LL mod)
 34 {
 35     LL sum=0;
 36     for(;b;b>>=1)
 37     {
 38         if(b&1LL)sum=(sum+a)%mod;
 39         a=(a+a)%mod;
 40     }
 41     return sum;
 42 }
 43 LL exgcd(LL a,LL b,LL &x,LL &y)
 44 {
 45     if(!b){x=1,y=0;return a;}
 46     LL d=exgcd(b,a%b,y,x);
 47     y-=a/b*x;
 48     return d;
 49 }
 50 LL china(int nn)
 51 {
 52     LL sum=0,tot=1,tott,x,y;
 53     int i;
 54     for(i=1;i<=nn;i++)if(u[i])tot*=p[i];
 55     for(i=1;i<=nn;i++)
 56     {
 57         if(!u[i])continue;
 58         tott=tot/p[i];
 59         exgcd(tott,p[i],x,y);
 60         x=(x%p[i]+p[i])%p[i];
 61         sum=((sum+cheng(a[i]*tott%tot,x,tot))%tot+tot)%tot;
 62     }
 63     sum=(r+tot-sum)/tot-(l-1+tot-sum)/tot;
 64     return sum;
 65 }
 66 int main()
 67 {
 68     #ifndef ONLINE_JUDGE
 69 //    freopen("1.txt","r",stdin);
 70 //    freopen("2.txt","w",stdout);
 71     #endif
 72     int i,j,k,ii;
 73 //    for(scanf("%d",&cas);cas;cas--)
 74     for(scanf("%d",&cas),cass=1;cass<=cas;cass++)
 75 //    while(~scanf("%s",s))
 76 //    while(~scanf("%d",&n))
 77     {
 78         ans=0;
 79         printf("Case #%d: ",cass);
 80         scanf("%d%lld%lld",&n,&l,&r);
 81         for(i=1;i<=n;i++)
 82             scanf("%lld%lld",&p[i],&a[i]);
 83         lll=1<<n;
 84         n++;
 85         u[n]=1;p[n]=7;a[n]=0;
 86         for(i=0;i<lll;i++)
 87         {
 88             for(j=i,k=0,ii=1;ii<n;j>>=1,ii++)
 89             {
 90                 u[ii]=j&1;
 91                 k+=u[ii];
 92             }
 93             k=k&1?-1:1;
 94             ans+=1LL*k*china(n);
 95         }
 96         printf("%lld\n",ans);
 97     }
 98     return 0;
 99 }
100 /*
101 //
102 
103 //
104 */
View Code

 

posted @ 2016-08-14 00:34  Cool639zhu  阅读(275)  评论(0编辑  收藏  举报