How many integers can you find(容斥+dfs容斥)

How many integers can you find

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

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-1中与M个数不互斥数的个数,由于4和6,12就可以除4和6,所以要找被选的数的最小公倍数;由于刚开始没考虑这点,直接找了24;注意M个数中可能有0;dfs+容斥,竟然运行时间还短点...

容斥代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
using namespace std;
typedef long long LL;
vector<LL>p;
LL gcd(LL a,LL b){return b==0?a:gcd(b,a%b);}
void rc(LL x){
    LL sum=0;
    for(int i=1;i<(1<<p.size());i++){
        LL num=0,cur=1;
        for(int j=0;j<p.size();j++){
            if(i&(1<<j)){
                num++;
                cur=cur*p[j]/gcd(cur,p[j]);
            }
        }//printf("%lld\n",cur);
        if(num&1)sum+=x/cur;
        else sum-=x/cur;
    }
    printf("%lld\n",sum);
}
int main(){
    LL N,M;
	LL x;
//	printf("%lld\n",(LL)pow(19,10));
    while(~scanf("%lld%lld",&N,&M)){
        p.clear();
        for(int i=0;i<M;i++){
            scanf("%lld",&x);
            if(x==0)continue;
            p.push_back(x);
        }
        rc(N-1);
    }
    return 0;
}

  dfs+容斥:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
using namespace std;
typedef long long LL;
LL m[15],ans;
LL N,M;
int k;
LL gcd(LL a,LL b){return b==0?a:gcd(b,a%b);}
void dfs(LL cur,LL pos,int t){
	if(t==0){
		if(k&1)ans+=N/cur;
		else ans-=N/cur;
		return;
	}
	if(pos>M)return;
	dfs(cur*m[pos]/gcd(cur,m[pos]),pos+1,t-1);
	dfs(cur,pos+1,t);
}
int main(){
	LL x;
//	printf("%lld\n",(LL)pow(19,10));
    while(~scanf("%lld%lld",&N,&M)){
    	N--;
        for(int i=1;i<=M;i++){
            scanf("%lld",&x);
            if(x==0)continue;
            m[i]=x;
        }
       ans=0;
       for(k=1;k<=M;k++){
       	dfs(1,1,k);
	   }
	   printf("%lld\n",ans);
    }
    return 0;
}

  

 

posted @ 2015-11-23 22:50  handsomecui  阅读(251)  评论(0编辑  收藏  举报