How many integers can you find
Time Limit: 12000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 3146 Accepted Submission(s): 891
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
Author
wangye
Source
Recommend
wangye
本题首先给出一个数n和m,以及m个数,要求小于n同时是m个数中任一个数的倍数的数的个数。
本题原理比较简单,容斥原理,保证既不遗漏又不重复。
本题的关键在于如何实现容斥原理。通常有两种方法,一种为暴力枚举(2^cnt),一中采用DFS搜索。
时间复杂度都相同O(2^cnt),但暴力的代码不好写,本题着重介绍DFS搜索。我采用的策略是从0到cnt,依次枚举当前数的所有组合情况,根据容斥原理,组合数为奇的加,为偶的减,考虑到了所有的组合情况又不遗漏。
此题数据较小不会超时也不会在中间过程中超出数的存储范围。
#include<iostream>
#include<cstdio>
#define LL __int64
using namespace std;
LL num[124],ans,n;
int cnt;
//求a,b的最大公约数
LL Gcd(LL a,LL b)
{
return b==0?a:Gcd(b,a%b);
}
//id表示起始位置,flag表示是添加还是去重,累加最小公倍数
void DFS(int id,bool flag,LL LCM)
{
LCM=LCM*num[id]/(Gcd(LCM,num[id]));
if(flag)ans+=n/LCM;
else ans-=n/LCM;
for(int i=id+1;i<cnt;i++)
{
DFS(i,!flag,LCM);
}
}
int main( )
{
int i,m;
while(~scanf("%I64d%d",&n,&m))
{
cnt=0;
for(i=0;i<m;i++)
{
scanf("%I64d",&num[i] );
if(num[i]!=0)
num[cnt++]=num[i];
}
ans=0;
n--;
for(i=0;i<cnt;i++)
{
DFS(i,true,num[i]);
}
printf("%I64d\n",ans);
}
return 0;
}