hdu 1796(容斥原理)
时间:2015-01-30 09:09:12
收藏:0
阅读:214
题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1796
How many integers can you find
Time Limit: 12000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4756 Accepted Submission(s): 1360
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
题意: 问在比n小的数里面,有多少个能被 M-integers set 中任意一个数整除的数?
思路:简单的容斥原理即可解决问题。 用A1表示能被第1个数整除的数的个数,A2表示能被第2个数整除的数的个数,....Am表示能被第m个数整除的数的个数。
现在就是要求A1+A2+...Am -两两重复+三三重复-四四重复+五五重复.... (注意0得排掉,不算)
通过dfs暴力枚举重复数即可
#include <iostream> #include <stdio.h> using namespace std; typedef long long ll; ll a[110],ans,n,m; int ct; ll gcd(ll a, ll b) { return b?gcd(b,a%b):a; } ll lcm(ll a,ll b) { return a/gcd(a,b)*b; } void dfs(int i,int cnt,ll sum,int pos) { if(cnt==pos) { sum=(n-1)/sum; (pos&1)?ans+=sum:ans-=sum; return ; } if(i==ct+1)return; ll tmp=lcm(a[i],sum); dfs(i+1,cnt+1,tmp,pos); dfs(i+1,cnt,sum,pos); } void cal() { ans=0; for(int i=1;i<=ct;i++) { dfs(1,0,1,i); } } int main() { while(cin>>n>>m) { ct=0; for(int i=1;i<=m;i++) { ll tmp; scanf("%I64d",&tmp); if(!tmp)continue; a[++ct]=tmp; } cal(); printf("%I64d\n",ans); } return 0; }
评论(0)