传送门
题意:求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;
}