hdu1796(容斥原理+最大公约数+DFS)

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个数中任一个数的倍数的数的个数。
本题原理比较简单,容斥原理,保证既不遗漏又不重复。
\left|A_1\cup A_2\cup\cdots\cup A_m\right|=
\sum_{1\le i\le m}\left|A_i\right|-\sum_{1\le i<j\le m}\left|A_i\cap A_m\right|+\sum_{1\le i<j<k\le m}\left|A_i\cap A_j\cap A_k\right|-\cdots+\left(-1^{m-1}\right)\left|A_1\cap A_2\cap\cdots\cap A_m\right|
本题的关键在于如何实现容斥原理。通常有两种方法,一种为暴力枚举(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;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值