这个题的m的数中居然有0啊,RE了好几次。。。。
初学容斥原理,这才知道还有奇加偶减这个东西,以前一直以为容斥原理不过是把重复的删掉就好了,。。
然后知道奇加偶减这个东西后,就可以深搜了,将所有组合情况全列出来,然后求lcm就好了。数的个数就是(n-1)/lcm,虽然我代码里写的是gcd。。不要在意这些细节。。。
#include <iostream>
#include <string.h>
#include <math.h>
#include <queue>
#include <algorithm>
#include <stdlib.h>
#include <map>
#include <set>
#include <stdio.h>
using namespace std;
#define LL __int64
const int mod=1e9+7;
const int INF=0x3f3f3f3f;
LL ans;
LL a[20], n, m;
int tot;
LL getgcd(LL x, LL y)
{
return y==0?x:getgcd(y,x%y);
}
void dfs(int cur, int cnt, LL gcd)
{
int i;
if(cur==tot) return ;
dfs(cur+1,cnt,1);
gcd=a[cur]/getgcd(gcd,a[cur])*gcd;
cnt++;
if(cnt&1)
ans+=n/gcd;
else
ans-=n/gcd;
dfs(cur+1,cnt,gcd);
}
int main()
{
int i;
LL x;
while(scanf("%I64d%I64d",&n,&m)!=EOF) {
tot=0;
for(i=0; i<m; i++) {
scanf("%I64d",&x);
if(x)
a[tot++]=x;
}
ans=0;
n--;
dfs(0,0,1);
printf("%I64d\n",ans);
}
return 0;
}
HDU 1796 How many integers can you find(容斥原理)
原文地址:http://blog.csdn.net/scf0920/article/details/42521955