HDU 1796 How many integers can you find (容斥定理)

http://acm.split.hdu.edu.cn/showproblem.php?pid=1796

How many integers can you find

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


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个数字(不大于20),求若一个数是这m个数字中的任意一个数字的倍数的话,那么这个数字就符合题意,求

【1,n),(不包括n)中有多少个这样的数字。

思路:容斥定理:每一个数字都能求出一些他的倍数,这些数字肯定都是符合题意的,但是有些数字重复计算了,所以要减去(用容斥定理解决),用这m个数字任意组合,个数为奇数则加上,个数为偶数则减去。(奇加偶减)

AC代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#define LL long long
using namespace std;
LL gcd(LL a,LL b)
{
    return b==0?a:gcd(b,a%b);
}
LL lcm(LL a,LL b)
{
    return a/gcd(a,b)*b;
}
int f[50],lf;
LL check(LL n)
{
    LL ans=0;
    int k=1<<lf;
    for(int i=1; i<k; i++)//枚举任意一个组合情况
    {
        LL tmp=1;
        int flag=0;
        for(int j=0; j<lf; j++)
            if(i&(1<<j))
            {
                tmp=lcm(tmp,(LL)f[j]);//求的是最小公倍数,而不是倍数
                flag++;//个数
            }
        if(flag&1) ans+=n/tmp;//奇加偶减
        else ans-=n/tmp;
    }
    return ans;
}
int main()
{
    int n,m;
    while(~scanf("%d%d",&n,&m))
    {
        int x[20];
        lf=0;
        for(int i=0; i<m; i++)
        {
            scanf("%d",&x[i]);
            if(x[i]) f[lf++]=x[i];
        }
        int ans=(int)check((LL)(n-1));
        printf("%d\n",ans);
    }
    return 0;
}











  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值