[CodeForces 273C] Primes on Interval (二分合法解)

CodeForces - 237C

给定正整数上的一段区间 [a,b] ,问是否存在长度 l(1lba+1)
使得任何 xi[a,bl+1] ,以 xi 开头,
长度为 l 的区间 [xi,xi+l1] 内都至少有 k 个质数
输出最小的 l ,若不存在,输出 1

很显然, l 越大,越可能有解,
先预处理出指数的前缀统计
然后二分 l ,然后逐位判断就好

#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <queue>
using namespace std;
typedef pair<int,int> Pii;
typedef long long LL;
typedef unsigned long long ULL;
typedef double DBL;
typedef long double LDBL;
#define MST(a,b) memset(a,b,sizeof(a))
#define CLR(a) MST(a,0)
#define Pow2(a) (a*a)

const int maxn=1e6+10;
int A,B,K;
bool npm[maxn];
int pmc[maxn];

void init();
bool judg(int);

int main()
{
    init();
    scanf("%d%d%d", &A, &B, &K);
    int l=1,r=B-A+1;
    while(l<r)
    {
        int mid=(l+r)>>1;
        if(judg(mid)) r=mid;
        else l=mid+1;
    }
    if(judg(l)) printf("%d\n", l);
    else puts("-1");
    return 0;
}

void init()
{
    for(int i=2; i<maxn; i++)
    {
        pmc[i]=pmc[i-1];
        if(npm[i]) continue;
        pmc[i]++;
        for(LL j=(LL)i*i; j<maxn; j+=i)
        {
            npm[j]=1;
        }
    }
}

bool judg(int len)
{
    for(int np=A; np<=B-len+1; np++)
    {
        if(pmc[np+len-1]-pmc[np-1]<K) return 0;
    }
    return 1;
}

你可能感兴趣的:(codeforces)