广州工业大学2016校赛 F 我是好人4 dfs+容斥

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

提示:数据是随机生成的,尔等尽可随意乱搞

思路:根据容斥原理;偶数就减,奇数就加;

   dfs需要优化:lcm>1e9;return;

   把0删掉,如果有整除的删掉;

#include<iostream>
#include<cstdio>
#include<cmath>
#include<string>
#include<queue>
#include<algorithm>
#include<stack>
#include<cstring>
#include<vector>
#include<list>
#include<set>
#include<map>
using namespace std;
#define ll long long
#define mod 1000000007
#define inf 999999999
int scan()
{
    int res = 0 , ch ;
    while( !( ( ch = getchar() ) >= '0' && ch <= '9' ) )
    {
        if( ch == EOF )  return 1 << 30 ;
    }
    res = ch - '0' ;
    while( ( ch = getchar() ) >= '0' && ch <= '9' )
        res = res * 10 + ( ch - '0' ) ;
    return res ;
}
ll a[55];
ll ans;
int y,len;
ll maxx=1e9;
ll gcd(ll x,ll y)
{
    if(x%y==0)
    return y;
    else
    return gcd(y,x%y);
}
void dfs(ll lcm,int pos,int step)
{
    if(lcm>maxx)
    return;
    if(pos==len)
    {
        if(step==0)
        return;
        if(step&1)
        ans+=(maxx/lcm);
        else
        ans-=(maxx/lcm);
        return;
    }
    dfs(lcm*a[pos]/gcd(lcm,a[pos]),pos+1,step+1);
    dfs(lcm,pos+1,step);
}
int main()
{
    int x,i;
    scanf("%d",&x);
    while(x--)
    {
        scanf("%d",&y);
        int lenn=0;
        for(i=0;i<y;i++)
        {
            scanf("%lld",&a[i]);
            if(a[i])
            a[lenn++]=a[i];
        }
        sort(a,a+lenn);
        len=0;
        for(int i=0;i<lenn;i++) {
               int  f = 0;
            for(int j=0;j<len;j++) {
                if(a[i]%a[j]==0) f=1;
            }
            if(!f) a[len++] = a[i];
        }
        ans=0;
        dfs(1,0,0);
        printf("%lld
",maxx-ans);
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/jhz033/p/5380269.html