How many integers can you find
Time Limit: 12000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 5493 Accepted Submission(s): 1567
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今天扣了一下容斥定理,离散结构中有,却是不记得了,总结一下,实现容斥原理大致有三种方法:dfs,队列数组,二进制,可以按照实际情况以及个人爱好自己选择容斥定理内容:
大家可以理解为奇数个的并集则是加,偶数个的并集则是减,具体的建议大家翻阅资料了解原理这道题目很明显符合容斥定理,所以我就用二进制过了![]()
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; typedef long long LL; const int MAXN = 50 + 5; int n, m; LL A[MAXN]; LL gcd(LL a,LL b) { return b ? gcd(b, a % b) : a; } LL lcm(LL a,LL b) { return a / gcd(a, b) * b; } int main() { while(~ scanf("%d%d", &n, &m)) { for(int i = 0; i < m; i ++) { scanf("%I64d", &A[i]); } int ms = 0; for(int i = 0 ;i < m;i ++){ if(A[i] == 0) continue; A[ms ++] = A[i]; } m = ms; LL ans = 0; for(int i = 1; i < (1 << m); i ++) { int bits = 0; LL res = 1; for(int j = 0; j < m; j ++) { if(i & (1 << j)) { bits ++; res = lcm(res, A[j]); } } if(bits & 1) ans += (LL)(n - 1) / res; else ans -= (LL)(n - 1) / res; } printf("%I64d\n", ans); } return 0; }