HDU1796 How many integers can you find(容斥)

来源:互联网 发布:网络录音电话 编辑:程序博客网 时间:2024/05/21 15:38

题意

给定a1,a2…am,求小于n的正整数至少能整除a中一个元素的数有几个?

思路

求[1,r)内有因子出现在集合中的数的个数。题目要求的数要么含有一个集合中的因子,要么是两个,要么是三个..要么是m个,而含两个集合中因子的数在计算含有一个集合中的因子,被重复计算了,三个时候也在计算二个的时候被重复计算,所以需要用到容斥原理。2^m枚举集合中元素,然后计算出最小公倍数,n/LCM就是1..n中含我们枚举的因子的数的个数对于求出来的数根据枚举到素因子个数奇数加偶数加。
这题有一个很坑的地方,a序列里有可能出现0,还有不包括n本身。。。被这个坑了好久。。。。这里枚举我直接二进制枚举,和状态压缩的道理差不多。。。

代码

#include <cstdio>#include <iostream>#define ll long longusing namespace std;const int kMaxn = 30 + 5;ll a[kMaxn];ll Gcd(ll x, ll y) {  if(x % y == 0)    return y;  return Gcd(y, x % y);}int main() {  int n,m;  while(~scanf("%d %d", &n, &m)) {    n--;    int t = 0;    for(int i = 0; i < m; i++) {      ll x;      scanf("%lld", &x);      if(x != 0) a[t++] = x;    }    m = t;    ll res = 0;    for(int i = 1; i < (1 << m); i++) {      int num = 0;      for(int j = i; j != 0; j = j >> 1) num += j & 1;      ll lcm = 1;      for(int j = 0; j < m; j++) {        if(i >> j & 1) {          //printf("%d ", a[j]);          lcm = lcm / Gcd(lcm, a[j]) * a[j];          if(lcm > n)            break;        }      }      //printf("\n");      if(num % 2 == 0) res -= n / lcm;      else res += n / lcm;    }    printf("%lld\n", res);  }  return 0;}
0 0
原创粉丝点击