【ZOJ - 2836】【Number Puzzle】(容斥定理)

版权声明:本人原创,未经许可,不得转载 https://blog.csdn.net/qq_42505741/article/details/83548552

题目:

Given a list of integers (A1, A2, ..., An), and a positive integer M, please find the number of positive integers that are not greater than M and dividable by any integer from the given list.

Input

The input contains several test cases.

For each test case, there are two lines. The first line contains N (1 <= N <= 10) and M (1 <= M <= 200000000), and the second line contains A1, A2, ..., An(1 <= Ai <= 10, for i = 1, 2, ..., N).

Output

For each test case in the input, output the result in a single line.

Sample Input

3 2
2 3 7
3 6
2 3 7
 

Sample Output

1
4

解题报告:确实刚上来是真的看不懂题目是意思,求解小于等于m的数能被数组中的n个数整除的数目和。打算直接遍历走完是不现实的,因为m的范围太大了, 所以想到了容斥定理,数组中的每个数字能被整除的数目的求并,自然引出容斥定理,然后套模板,最后做差输出即可。

ac代码:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;

int num[15],n,m;
int gcd(int a,int  b)
{
	if(b==0)
		return a;
	else
		return gcd(b,a%b);	
} //最大公因子 
int lcm(int a,int b)
{
	return a/gcd(a,b)*b;
}//最小公倍数 
int dfs(int pos,int val)
{
	if(pos==n)
	{
		return m/val;
	}
	return dfs(pos+1,val)-dfs(pos+1,lcm(val,num[pos]));
}
//容斥定理 
int main()
{
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		for(int i=0;i<n;i++)
			scanf("%d",&num[i]);
		printf("%d\n",m-dfs(0,1));
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42505741/article/details/83548552