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

版权声明:欢迎学习我的博客,希望ACM的发展越来越好~ https://blog.csdn.net/qq_41289920/article/details/83656185

题干:

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

题目大意:

给N个整数,和一个整数M。求小于等于M的非负整数(1~M)中能被这N个数中任意一个整除的数的个数。

解题报告:

   裸的容斥原理啊不解释了。。。

AC代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<map>
#include<vector>
#include<set>
#include<string>
#include<cmath>
#include<cstring>
#define ll long long
#define pb push_back
#define pm make_pair
#define fi first
#define se second
using namespace std;
const int MAX = 2e5 + 5;
ll ans,m,n;
ll a[105];
ll LCM(ll a,ll b) {
	return (a*b)/__gcd(a,b);
}
void dfs(ll cur,ll lcm,ll id) {
	if(cur == n) {
		if(id == 0) return ;
		if(id&1) ans += ((m)/lcm);
		else ans-=((m)/lcm);
		return ;
	}
	dfs(cur+1,lcm,id);
	dfs(cur+1,LCM(a[cur+1],lcm),id+1);
}
int main()
{
	while(~scanf("%lld%lld",&n,&m)) {
		for(int i = 1; i<=n; i++) scanf("%lld",a+i);
		ans=0;
		dfs(1,a[1],1);//没选第一个 
		dfs(1,1,0);//选了第一个 
		printf("%lld\n",ans);
	}

	return 0 ;
 }

猜你喜欢

转载自blog.csdn.net/qq_41289920/article/details/83656185