M - How many integers can you find HDU - 1796

Now you get a number N, and a M-integers set, you should find out how many integers which are small than N, that they can divided exactly by any integers in the set. For example, N=12, and M-integer set is {2,3}, so there is another set {2,3,4,6,8,9,10}, all the integers of the set can be divided exactly by 2 or 3. As a result, you just output the number 7.
Input  There are a lot of cases. For each case, the first line contains two integers N and M. The follow line contains the M integers, and all of them are different from each other. 0<N<2^31,0<M<=10, and the M integer are non-negative and won’t exceed 20. Output  For each case, output the number. Sample Input
12 2
2 3
Sample Output
7

題解:先去除0,再利用隊列進行容斥(由於給出的數並不是兩兩互質,所以要求lcm)

#include<iostream>
#include<string.h>
#include<stdio.h>
#include<cmath>
using namespace std;
typedef long long ll;
const int maxn=10005;
int N,m,q[maxn],a[15],vis[15];
int gcd(int a,int b){
    return b?gcd(b,a%b):a;
}
int main(){
    while(scanf("%d%d",&N,&m)!=EOF){
        N--;
        memset(vis,0,sizeof(vis));
        for(int i=0;i<m;i++) scanf("%d",&a[i]);
        for(int i=0;i<m;i++)
            if(!a[i]) vis[i]=1;
        ll ans=0;int n=0;q[n++]=-1;
        for(int i=0;i<m;i++){
            if(vis[i]) continue;
            int tmp=n;
            for(int j=0;j<tmp;j++)
                q[n++]=q[j]/abs(gcd(q[j],a[i]))*a[i]*(-1);
        }
        for(int i=1;i<n;i++)
            ans+=N/q[i];
        printf("%lld\n",ans);
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章