HDU 1796 How many integers can you find

 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
题解:基本容斥;我们可用二进制压缩,枚举每一个状态。加上奇数的倍数,减去偶数个个数的倍数;
参考代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
LL n,m,a[11],num[1<<11],cnt,ans;

LL work(int x)
{
    LL flag1=1,flag2=1;
    for(int i=0;i<=m-1;i++)
    {
        LL temp=1<<i;
        if(x&temp) cnt++,flag2=__gcd(a[i],flag1),flag1=a[i]*flag1/flag2;
    }
    return flag1;
} 

int main()
{
    while(~scanf("%lld%lld",&n,&m))
    {
        ans=0;
        for(LL i=0;i<m;i++)
        {
            scanf("%lld",a+i);
            if(a[i]==0) i--,m--;    
        } 
        for(LL i=1;i<(1<<m);i++)
        {
            cnt=0;
            LL sum=work(i);
            if(cnt&1) ans=ans+(n-1)/sum;
            else ans=ans-(n-1)/sum;
        }
        printf("%d
",ans);
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/csushl/p/9498451.html