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): 5331    Accepted Submission(s): 1513


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
 

题意:给定一个有m个数组成的集合,问你在区间[1, n-1] 里面有多少个数能被集合里面至少一个元素整除。

 

思路:题目给出的集合和我们平常所求的存储质因子的数组有所不同。存储质因子的数组里面的任意两个数都是互质的,(用以前的思路直接奇加偶减(n - 1) / A*B即可),但题目所给的集合中任意两个数可能会有除了1之外的公约数,我们这里不能直接那样算,因为多算了lcm(A, B) 的情况。这里若用队列实现容斥原理会很麻烦,我没写出来,因为用队列求的lcm会有负数。。。没办法花了点时间看了位运算求法,挺很好理解的。

 

提醒:这道题给出的集合里面会有0 或者 >= n的元素; 还有没有必要用long long 或者 __int64, 因为超int是出现在求lcm的时候(20的阶乘超int),我们在求lcm时 这样写就不会超int了:return a / gcd(a, b) *b; 先除一下再乘。

 

#include <cstdio>
#include <cstring>
#include <cstdlib>
int p[22], k;
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 nop(int m)
{
	int i, j;
	int res;
	int sum = 0;
	int use;//记录使用因子的个数 
	for(i = 1; i < 1<<k; i++)
	{
		res = 1; use = 0;
		for(j = 0; j < k; j++)
		{
			if(i & (1<<j))
			{
				use++;
				res = lcm(res, p[j]);
			}
		}
		if(use & 1) sum += m / res;//奇加偶减 
		else sum -= m / res;
	}
	return sum;
}
int main()
{
	int n;
	int i, j;
	while(scanf("%d%d", &n, &k) != EOF)
	{
		for(i = 0; i < k; i++)
		{
			scanf("%d", &p[i]);
			if(p[i] < 1 || p[i] >= n)
			i--, k--;
		}
		printf("%d\n", nop(n-1));
	}
	return 0;
}


 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值