How many integers can you find
Time Limit: 12000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 13231 Accepted Submission(s): 3968
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
2008 “Insigma International Cup” Zhejiang Collegiate Programming Contest - Warm Up(4)
Recommend
wangye | We have carefully selected several similar problems for you: 1793 1794 1797 1795 1798
题意:
给出两个数N(0<N<231)和M(0<M<=10),M是一个不超过10个元素的非负整数集合,元素值不超过20. 求出在小于N的整数中满足“能整除M集合里其中一个元素”的元素个数。
比如N=12, M{2,3}, 满足的集合为{2,3,4,6,8,9,10},该集合元素个数为7,就输出7.
思路分析:
分析样例,11里面整除2的为2,4,6,8,10. 个数为[11/2]。11里面整除3的为3,6,9. 个数为[11/3]。
其中,6被重复计算了一次,需要减掉。这个6就是2和3的最小公倍数。因此需要减掉[11/6]。
可以发现这种计算模式就是容斥定理。相交部分就是最小公倍数。
容斥定理核心概念为“奇加偶减”。
举个例子,N=15, M = 3, 集合为{2,5,7},[a,b]表示lcm(a,b),那么ans = f(2) + f(5) + f(7) - f([2,5]) - f([2,7]) - f([5,7]) + f([2,5,7]).
我们改变一下排列方式
2
2 5
2 5 7
2 7
5
5 7
7
这时可以很明显的发现这个就是类似于子集生成的dfs,个数为奇数时加,个数为偶数时减。
下面上AC代码
#include <iostream>
#define ll long long
using namespace std;
ll ans, N, M, a[100];
ll gcd(ll a,ll b){
return b == 0?a:gcd(b,a%b);
}
void dfs(ll cur, ll lcm, ll id)
{
lcm = a[cur]*lcm/gcd(lcm,a[cur]);
// cout<<cur<<" "<<lcm<<endl;
if(id&1) ans += (N-1)/lcm; //读取id最后一个二进制位,若为1,则id为奇数。
else ans -= (N-1)/lcm;
for(int i = cur+1;i < M;i++)
dfs(i, lcm, id+1);
}
int main()
{
while(cin>>N>>M)
{
ans = 0;
ll t = 0;
ll MM = M;
while(MM--)
{
ll x;
cin>>x;
if(x) a[t++] = x; //去除0
}
for(int i = 0;i < M;i++)
dfs(i,a[i],1);
cout<<ans<<endl;
}
return 0;
}