广东工业大学2016校赛决赛-网络赛 1174 Problem F 我是好人4 容斥

Problem F: 我是好人4

Description

众所周知,我是好人!所以不会出太难的题,题意很简单

给你n个数,问你1000000000(含1e9)以内有多少个正整数不是这n个数任意一个的倍数

最后友情提供解题代码(我真是太好人了)

void solve(int p[], int n)

{

int ans = 0;

for (int i = 1; i <= 1e9; i++)

{

int fl = 0;

for (int j = 0; j < n; j++)

{

if (i % p[j] == 0)

{

fl = 1;

break;

}

}

if (fl == 0)ans++;

}

printf("%d ", ans);

}

Input

第1行是一个整数T,表示共T组数据。 接下来是T组数据,每组数据第1行是正整数n(n<=50),接下来是n个正整数(小于等于1000),任意两数用1个空格隔开,最前数前面与最后数后面无空格

Output

输出T行,对应T组数据。(T<=10) 每行输出这样的正整数有多少个

Sample Input

3 4 2 3 5 7 1 2 13 854 101 143 282 538 922 946 286 681 977 892 656 907

Sample Output

228571428 500000000 968701719

HINT

题解:

  乍一看n<=50,直接容斥会崩,考虑到计算1e9内的数,

  想到最多就是9个数的样子,

  在dfs容斥的时候假如一个条件超过1e9就跳出就好了

  还有一个优化就是 n个数可能含有倍数关系这个去掉

  去重

 

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 1e5+10, M = 1e5, mod = 1e9, inf = 1e9+9;
typedef long long ll;
ll ans;
ll a[100];
int m;
ll gcd(ll a,ll b){if(b==0) return a;return gcd(b,a%b);}
void dfs(int i,int num,ll tmp){
    if(tmp>mod) return ;
    if(i>=m){
        if(num==0){
            ans=0;
        }
        else if(num&1)ans=(ans+mod/tmp);
        else ans=ans-mod/tmp;
        return ;
    }
    dfs(i+1,num,tmp);
    dfs(i+1,num+1,tmp*a[i]/gcd(tmp,a[i]));
}
int main(){
    bool flag;
    int T;
    scanf("%d",&T);
    while(T--) {
        scanf("%d",&m);
        flag=true;
        int k=0;
        for(int i=0;i<m;i++){
            scanf("%I64d",&a[i]);
            if(a[i])
            a[k++]=a[i];
        }
        m=0;
        sort(a,a+k);
        for(int i=0;i<k;i++) {
               int  f = 0;
            for(int j=0;j<m;j++) {
                if(a[i]%a[j]==0) f=1;
            }
            if(!f) a[m++] = a[i];
        }
        ans=0;
        dfs(0,0,1);
        printf("%lld
",mod - ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zxhl/p/5375456.html