hdu 1796 How many integers can you find(容斥原理)

来源:互联网 发布:ida远程调试linux 编辑:程序博客网 时间:2024/05/16 15:24

How many integers can you find

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


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 22 3
 

Sample Output
7
 

题意如上 很简单

思路:以样例来说  因为要是比12小的  所以最大是11 是2的倍数的有5个 是3的倍数的有3个  因为把6多算了一次  所以要减去1  这样就是7个数 符合要求 

容斥原理:

先分别求出对每个数符合要求的在小于n的范围内的个数  然后每两个数之间的最小公倍数的K倍是多算的 再减去

然后每三个数之间的最小公倍数的K倍是又少算了的  再加上。。。如此递推下去 

用dfs模拟容斥的过程 

注意 题意中数据是非负数 所以可能会出现0  

#include <cstdio>#include <iostream>#include <cstring>#include <cmath>#include <algorithm>#include <string.h>#include <string>#define eps 1e-8#define op operator#define MOD  10009#define MAXN  100100#define INF 0x7fffffff#define FOR(i,a,b)  for(int i=a;i<=b;i++)#define FOV(i,a,b)  for(int i=a;i>=b;i--)#define REP(i,a,b)  for(int i=a;i<b;i++)#define REV(i,a,b)  for(int i=a-1;i>=b;i--)#define MEM(a,x)    memset(a,x,sizeof a)#define ll __int64using namespace std;ll a[25];ll n,m;ll ans;ll gcd(ll b,ll c){    if(c==0)  return b;    return gcd(c,b%c);}ll lcm(ll b,ll c){    return (b*c)/(gcd(b,c));}void dfs(int order,ll x,int b){//    cout<<"order  "<<order<<endl;    for(int i=order;i<m;i++)    {        if(a[i])        {            ll c=lcm(x,a[i]);//最小公倍数            ll cnt=n/c; //个数//        cout<<"cnt  "<<cnt<<" bb "<<b<<endl;            ans+=b*cnt;            dfs(i+1,c,-b);        }    }    return;}int main(){//freopen("ceshi.txt","r",stdin);    while(scanf("%I64d%I64d",&n,&m)!=EOF)    {        n--;        for(int i=0;i<m;i++)        {            scanf("%I64d",&a[i]);        }        ans=0;        dfs(0,1,1);        printf("%I64d\n",ans);    }    return 0;}





  

0 0
原创粉丝点击