容斥C - How many integers can you find HDU - 1796

题目链接http://acm.hdu.edu.cn/showproblem.php?pid=1796

题意:给定一个数n,数列m个数,求这小于n的数中,有多少个数满足能被这m个数中任意一个数整除。

递归容斥,把每种情况算出, 然后容斥一下,这里 注意 例如2 3 6,不能直接把他们相乘,他们的 最小公倍数为12,需要用gcd一下

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<math.h>
#include<set>
#include<vector>
#include<sstream>
#include<queue>
#define ll long long
#define PI 3.1415926535897932384626
#define inf 0x3f3f3f3f
ll gcd(ll a,ll b){
    return b?gcd(b,a%b):a;
}
using namespace std;
long long ans;
ll n,m;
int tot;
int M[30];
void dfs(int v,int pos,ll num)
{
    ll temp;
    for(int i=v;i<tot;i++)
    {
        temp=num*M[i]/gcd(num,M[i]);

        if(pos&1){
            ans+=(n-1)/temp;
        }
        else{
            ans-=(n-1)/temp;
        }
        dfs(i+1,pos+1,temp);
    }
}
int main()
{
    while(scanf("%lld%lld",&n,&m)!=EOF)
    {
        tot=0;
        for(int i=0;i<m;i++){
            int t;
            scanf("%d",&t);
            if(t>0&&t<n)M[tot++]=t;
        }
        ans=0;
        dfs(0,1,1);
        printf("%lld\n",ans);
    }
    return 0;
}

递归容斥模板

//容斥原理,结果存在sub中
long long sub = 0;
void dfs(int id,int deep,long long sum)
{
  //  cout<<sum<<endl;
    long long temp;
    for(int i = id; i < primenum; i ++)
    {
        temp = sum * prime[i];
      //  cout<<temp<<endl;
        if(temp  > n) //避免溢出
        {
            return;
        }
        if(deep % 2 == 0)
        {
            sub -= n / temp;
        }
        else
        {
            sub += n / temp;
        }
 
        dfs(i + 1,deep + 1,temp);//deep,集合重叠的个数
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41568836/article/details/82181108