首页 > 代码库 > hdu 1796 How many integers can you find【容斥原理】

hdu 1796 How many integers can you find【容斥原理】

How many integers can you find

Time Limit: 12000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4674    Accepted Submission(s): 1340


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和M,接下来给出一个M个元素的集合,求1-(N-1)中,有多少个数字是集合中任意元素的倍数!最后只写个数!
解题思路:还是利用容斥原理来求,只不过这次给你的集合貌似就是以前所求的p数组元素,但是他和p数组元素的要求又有所不同,因为以前所求的p数组元素只有素数,且任意元素都不相同,但是这一次的却是很混杂,只说是给的非负数,因此我们在求的时候首先要求掉一些无关元素,比如:0和大于N的数字,这一步输入的时候处理!
再其次,容斥原理减去重叠元素的时候,按照以前的,假如素因子分别是A和B,则我们要减去N/(A*B),但是对于本题,由于A,B可能存在公约数,我们却要算的是N除以lcm(A,B),lcm是最小公倍数,具体算法如下:
#include <stdio.h>
#include <algorithm>
using namespace std;
int p[12],top,ans,n;
int gcd(int a,int b){
    return b?gcd(b,a%b):a;
}
int lcm(int a,int b){
    return a/gcd(a,b)*b;
}
int nop(int m){
    int i,j,sum=0,flag,num;
    for(i=1;i<1<<top;i++){
        flag=0;
        num=1;
        for(j=0;j<top;j++)
            if(i&(1<<j))
                flag++,num=lcm(num,p[j]);
        if(flag&1) sum+=m/num;
        else       sum-=m/num;
    }
    return sum;
}
int main(){
    while(~scanf("%d%d",&n,&top)){
        for(int i=0;i<top;i++){
            scanf("%d",&p[i]);
            if(p[i]<1||p[i]>=n)
                i--,top--;
        }
        printf("%d\n",nop(n-1));
    }
    return 0;
}

hdu 1796 How many integers can you find【容斥原理】