hdu1796(容斥原理基本运用)

传送门
题意:求n以内能够被所给的集合中的数整除的数的个数。 

思路:很容易想到容斥原理,先找出1...n内能被集合中任意一个元素整除的个数,再减去能被集合中任意两个整除的个数,即能被它们两只的最小公倍数整除的个数,因为这部分被计算了两次,然后又加上三个时候的个数,然后又减去四个时候的倍数...所以深搜,最后判断下集合元素的个数为奇还是偶,奇加偶减。 为什么是最小公倍数 比如(6,9)其实18的时候他们就重复计算了

二进制模版

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin >> n;
    for(int i = 0; i < (1<<n); i++) //从0~2^n-1个状态
    {
        for(int j = 0; j < n; j++) //遍历二进制的每一位
        {
            if(i & (1 << j))//判断二进制第j位是否存在
            {
                printf("%d ",j);//如果存在输出第j个元素
            }
        }
        printf("\n");
    }
    return 0;
}
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int arr[20];
int main()
{
	int n,m;
	while(cin>>n>>m)
	{
		 int tot=0;
		 for(int i=1;i<=m;i++)
		 {
		 	int x;//注意0这种情况 
		 	cin>>x;
			if(x!=0)
			arr[tot++]=x;
		 }
		 int ans=0;
		 for(int i=1;i<(1<<tot);i++)
		 {
		 	int lcm=1,id=0;
		 	for(int j=0;j<tot;j++)
		 	{
		 		if(i&(1<<j))
		 		{
		 			id++;
		 			lcm=lcm/__gcd(lcm,arr[j])*arr[j];
		 		}
		 	}
		 	if(id%2==0)
		 	{
		 		ans-=(n-1)/lcm;
		 	}
		 	else
		 	{
		 		ans+=(n-1)/lcm;
		 	}
		 }
		 cout<<ans<<endl;
	}
	return 0;
}

DFS版

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
int arr[25];
int ans;
int tot;
int n,m;

void dfs(int a,int lcm,int id)
{
	lcm=arr[a]/__gcd(lcm,arr[a])*lcm;
	if(id%2==0)
	{
		ans-=(n-1)/lcm;
	}
	else
	{
		ans+=(n-1)/lcm;
	}
	for(int i=a+1;i<tot;i++)
	{
		dfs(i,lcm,id+1);
	} 
}
int main()
{
	while(cin>>n>>m)
	{
		 tot=0;
		 ans=0;
		 for(int i=1;i<=m;i++)
		 {
		 	int x;//注意0这种情况 
		 	cin>>x;
			if(x!=0)
			arr[tot++]=x;
		 }
		 for(int i=0;i<tot;i++)
		 {
		 	dfs(i,arr[i],1);
		 }
		 cout<<ans<<endl;
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值