1. 程式人生 > >[容斥原理] hdu 1796 How many integers can you find

[容斥原理] hdu 1796 How many integers can you find

pos lcm 一個 每一個 fin memset 而不是 std !=

題意:

給一個N。然後給M個數,問1~N-1裏面有多少個數能被這M個數中一個或多個數整除。

思路:

首先要N--

然後對於每一個數M 事實上1~N-1內能被其整除的 就是有(N-1)/M[i]個

可是會出現反復 比方 例子 6就會被反復算

這時候我們就須要容斥原理了

加上一個數的減去兩個數的。。

這裏要註意了 兩個數以上的時候 是求LCM而不是簡單的相乘!

代碼:

#include "stdio.h"
#include "string.h"
#include "math.h"
#include "iostream"
#include "cstdlib"
#include "algorithm"
#include "queue"
using namespace std;
int a[12];
int used[12],b[12];
int n,m;
int gcd(int a,int b)
{
    return b==0?a:gcd(b,a%b);
}
int lcm(int k)
{
    int ans=b[0];
    for(int i=1;i<k;i++)
    {
        int tep=gcd(ans,b[i]);
        ans=ans/tep*b[i];
    }
    return ans;
}
__int64 dfs(int kk,int x,int lit)
{
    __int64 ans=0;
    if(x==lit)
    {
        int tep;
        tep=lcm(x);
        return n/tep;
    }
    for(int i=kk+1;i<m;i++)
    {
        if(a[i]==0) continue;
        if(used[i]) continue;
        used[i]=1;
        b[x]=a[i];
        ans+=dfs(i,x+1,lit);
        used[i]=0;
    }
    return ans;
}
int main()
{
    while(scanf("%d%d",&n,&m)!=-1)
    {
        n--;
        for(int i=0;i<m;i++) scanf("%d",&a[i]);
        __int64 ans=0;
        for(int i=1;i<=m;i++)
        {
           // printf("%d\n",dfs(-1,0,i));
            memset(used,0,sizeof(used));
            if(i%2==0) ans-=dfs(-1,0,i);
            else ans+=dfs(-1,0,i);
        }
        printf("%I64d\n",ans);
    }
    return 0;
}



[容斥原理] hdu 1796 How many integers can you find