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

How many integers can you find

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


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中的数整除的数的个数

思路:很明显的容斥原理,如果马虎一看肯定就直接把m集合的数当成aprime数组写了,(其实我是这样的衰= =),
但是这个m集合并不是全为素数,所以说就不能那样求了,为素数的时候当前个数为num/a*b,但是a和b可能会存在公约数,所以说就变成了num/lcm(a,b),当然后面多个也是一样。。

WA点:1.集合m中可能会存在0,这个是导致RE的原因,应消去这些0
             2.因为我用的是队列法求的,所以说如果读者也是用队列法,那么注意一下que数组的正负



ac代码:
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stack>
#include<set>
#include<queue>
#include<vector>
#include<iostream>
#include<algorithm>
#define MAXN 100010
#define LL long long
#define ll __int64
#define INF 0x7fffffff
#define mem(x) memset(x,0,sizeof(x))
#define PI acos(-1)
#define eps 1e-10
using namespace std;
int gcd(int a,int b){return b?gcd(b,a%b):a;}
int lcm(int a,int b){return a/gcd(a,b)*b;}
LL powmod(LL a,LL b,LL MOD){LL ans=1;while(b){if(b%2)ans=ans*a%MOD;a=a*a%MOD;b/=2;}return ans;}
//head
LL m[MAXN];
LL cnt;
LL fun(LL num)
{
	LL que[MAXN],i,j,kk,ans=0,t=0;
	que[t++]=-1;
	for(i=0;i<cnt;i++)
	{
		kk=t;
		for(j=0;j<kk;j++)
		{
			if(que[j]<0)
			que[t++]=lcm(m[i],-que[j]);
			else
			que[t++]=lcm(m[i],que[j])*(-1);
		}
		
	}
	for(i=1;i<t;i++)
	ans+=(num/que[i]);
	return ans;
}
int main()
{
	LL num,n,k;
	while(scanf("%lld%lld",&n,&k)!=EOF)
	{
		cnt=0;
		for(int i=0;i<k;i++)
		{
			scanf("%lld",&num);
			if(num)
			m[cnt++]=num;
		}
		printf("%lld\n",fun(n-1));
	}
	return 0;
}


你可能感兴趣的:(HDOJ 1796 How many integers can you find (容斥原理))