How many integers can you find
Time Limit: 12000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4249 Accepted Submission(s):
1211
Problem Description
Now you get a number N, and a M-integers set, you
should find out how many integers which are small than N, that they can divided
exactly by any integers in the set. For example, N=12, and M-integer set is
{2,3}, so there is another set {2,3,4,6,8,9,10}, all the integers of the set can
be divided exactly by 2 or 3. As a result, you just output the number 7.
Input
There are a lot of cases. For each case, the first
line contains two integers N and M. The follow line contains the M integers, and
all of them are different from each other. 0<N<2^31,0<M<=10, and the
M integer are non-negative and won’t exceed 20.
Output
For each case, output the number.
Sample Input
12 2
2 3
Sample Output
7
题意:给n个数字,最大不会超过20的非负数,0忽略它可以。给你一个数字M,
问1-M-1中,有多少个数字能被这n数字中任何一个整除(只要满足其中一个能整除就行)。统计个数输出。
思路:容斥,简单容斥。一开始做zoj的一道题,果断数据太水,方法是不对的也能ac。
原来的思路是这样的,对n个数字,筛选掉ai倍数的数字,然后就容斥,但是明显这样的数据有问题
4 6, 这样容斥后得到的结果是4 6 -24,不对的,应该是4 6 -12,所以应该是 4 6 -(4*6)/gcd(4,6)
略坑略坑。
1 #include<iostream> 2 #include<stdio.h> 3 #include<cstring> 4 #include<cstdlib> 5 using namespace std; 6 7 bool Hash[22]; 8 int f[22],len,qlen; 9 __int64 Q[5002]; 10 11 int gcd(int a,int b) 12 { 13 if(a<0)a=-a; 14 if(b<0)b=-b; 15 if(b==0)return a; 16 int r; 17 while(b) 18 { 19 r=a%b; 20 a=b; 21 b=r; 22 } 23 return a; 24 } 25 void solve(__int64 m) 26 { 27 qlen = 0; 28 Q[0]=-1; 29 for(int i=1;i<=len;i++) 30 { 31 int k=qlen; 32 for(int j=0;j<=k;j++) 33 Q[++qlen]=-1*(Q[j]*f[i]/gcd(Q[j],f[i])); 34 } 35 __int64 sum = 0; 36 for(int i=1;i<=qlen;i++) 37 sum = sum+m/Q[i]; 38 printf("%I64d ",sum); 39 } 40 int main() 41 { 42 int m,x; 43 __int64 n; 44 while(scanf("%I64d%d",&n,&m)>0) 45 { 46 n=n-1; 47 memset(Hash,false,sizeof(Hash)); 48 for(int i=1;i<=m;i++) 49 { 50 scanf("%d",&x); 51 Hash[x]=true; 52 } 53 for(int i=1;i<=20;i++) 54 { 55 if(Hash[i]==true) 56 for(int j=i+i;j<=20;j=j+i) 57 if(Hash[j]==true) Hash[j]=false; 58 } 59 len = 0; 60 for(int i=1;i<=20;i++)if(Hash[i]==true) f[++len]=i; 61 solve(n); 62 } 63 return 0; 64 }