[BZOJ2986]Non-Squarefree Numbers(二分+容斥原理)

题目描述

传送门

题解

和BZOJ2440基本一样,只不过是补集而已
用莫比乌斯函数当容斥系数

代码

#include
#include
#include
#include
#include
using namespace std;
#define N 300005
#define LL long long

LL n,ans,mu[N];
int p[N],prime[N];

void get(int n)
{
    mu[1]=1;
    for (int i=2;i<=n;++i)
    {
        if (!p[i])
        {
            prime[++prime[0]]=i;
            mu[i]=-1;
        }
        for (int j=1;j<=prime[0]&&i*prime[j]<=n;++j)
        {
            p[i*prime[j]]=1;
            if (i%prime[j]==0)
            {
                mu[i*prime[j]]=0;
                break;
            }
            else mu[i*prime[j]]=-mu[i];
        }
    }
}
LL calc(LL n)
{
    LL ans=0;
    for (LL i=2;i*i<=n;++i)
        ans-=mu[i]*n/(i*i);
    return ans;
}
void find()
{
    LL l=0,r=30000000000LL,mid;
    while (l<=r)
    {
        mid=(l+r)>>1;
        LL now=calc(mid);
        if (now1;
        else ans=mid,r=mid-1;
    }
}
int main()
{
    get(300000);
    scanf("%lld",&n);
    find();
    printf("%lld\n",ans);
}

你可能感兴趣的:(题解,二分,容斥原理)