lightoj1117(容斥定理)

Cicada is an insect with large transparent eyes and well-veined wings similar to the "jar flies". The insects are thought to have evolved 1.8 million years ago during the Pleistocene epoch. There are about 2,500 species of cicada around the world which live in temperate tropical climates.

These are all sucking insects, which pierce plants with their pointy mouthparts and suck out the juices. But there are some predators (like birds, the Cicada Killer Wasp) that attack cicadas. Each of the predators has a periodic cycle of attacking Cicadas. For example, birds attack them every three years; wasps attack them every 2 years. So, if Cicadas come in the 12th year, then birds or wasps can attack them. If they come out in the 7th year then no one will attack them.

So, at first they will choose a number N which represents possible life-time. Then there will be an integer M indicating the total number of predators. The next M integers represent the life-cycle of each predator. The numbers in the range from 1 to N which are not divisible by any of those Mlife-cycles numbers will be considered for cicada's safe-emerge year. And you want to help them.

Input

Input starts with an integer T (≤ 125), denoting the number of test cases.

Each case contains two integers N (1 ≤ N < 231) and M (1 ≤ M ≤ 15). The next line contains Mpositive integers (fits into 32 bit signed integer) denoting the life cycles of the predators.

Output

For each test case, print the case number and the number of safe-emerge days for cicada.

Sample Input

2

15 3

2 3 5

10 4

2 4 5 7

Sample Output

Case 1: 4

Case 2: 3

题意:第一行t表示测试用例数。

对于每个样例第1行两个数n和m。

第二行m个数。求1-n中有多少个数不能被这m个数中任意一个整除。

思路:

我们求<=n的数是这m个数倍数的个数。然后用n减去这些数。
,这就需要容斥原理。AUBUC=A+B+C-A∩B-A∩C-B∩C+A∩B∩C(奇加偶减)

代码 ;

#include <string.h>
#include <stdio.h>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
ll gcd(ll a,ll b)
{
	return b==0?a:gcd(b,a%b);
}
ll lcm(ll a,ll b)
{
	return a*b/gcd(a,b);
}
ll a[19];
ll bit(ll n)
{
	ll ans=0;
	while(n)
	{
		if(n%2==1)ans++;
		n>>=1;
	}
	return ans;
}
int main()
{
	ll t,n,m;
	cin>>t;
	ll b[105];ll cas=1;
	while(t--)
	{
		cin>>n>>m;
		ll ans=0;
		for(ll i=0;i<m;i++)
		cin>>a[i];
		
		for(ll i=1;i<=m;i++)
		{
			ll num=0,sum=0;
			for(ll k=0;k<(1<<m);k++)
			{
				if(bit(k)==i)
				{
					ll op=1;
					for(ll j=0;j<m;j++)
					{
						if((1<<j)&k) op=lcm(op,a[j]);
					}
					sum+=n/op;
				}
			}
			if(i%2==0) ans-=sum;
			else ans+=sum;
		}
		
		printf("Case %lld: %lld\n",cas++,n-ans);
	}
	return 0;
}

 

猜你喜欢

转载自blog.csdn.net/qq_40859951/article/details/88823138