hdu 1796(容斥原理+状态压缩)

Posted AC菜鸟机

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hdu 1796(容斥原理+状态压缩)相关的知识,希望对你有一定的参考价值。

How many integers can you find

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


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
 
题意:在 1-(n-1) 中能够被输入的数字整除的数字的数量。
思路:容斥原理+枚举状态,碰到奇数加上(n-1)/lcm(a,b,c..) 碰到偶数减(n-1)/lcm(a,b,c...) 注意0不能取,发现本人一直不是很会用深搜,所以还是用状压了 = =
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <stdlib.h>
#include <math.h>
using namespace std;
int gcd(int a,int b){
    return b==0?a:gcd(b,a%b);
}
int lcm(int a,int b){
    return a/gcd(a,b)*b;
}
int main()
{
    int n,m,a[15];
    while(scanf("%d%d",&n,&m)!=EOF){
        int id = 0,num;
        for(int i=0;i<m;i++){
            scanf("%d",&num);
            if(num!=0) a[id++] = num;
        }
        int ans = 0;
        for(int i=1;i<(1<<id);i++){
            int l=1,cnt=0;
            for(int j=0;j<id;j++){
                if((i>>j)&1){
                    cnt++;
                    l = lcm(l,a[j]);
                }
            }
            if(cnt&1){
                ans+=(n-1)/l; ///不包括自身所以n-1
            }else{
                ans-=(n-1)/l;
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

以上是关于hdu 1796(容斥原理+状态压缩)的主要内容,如果未能解决你的问题,请参考以下文章

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

[容斥原理] hdu 1796 How many integers can you find

hdu1796 How many integers can you find 容斥原理

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

HDU 1796 How many integers can you find(容斥原理+二进制/DFS)

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