Primes on Interval(CF-237C)
Problem Description
You've decided to carry out a survey in the theory of prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors.
Consider positive integers a, a?+?1, ..., b (a?≤?b). You want to find the minimum integer l (1?≤?l?≤?b?-?a?+?1) such that for any integer x (a?≤?x?≤?b?-?l?+?1) among l integers x, x?+?1, ..., x?+?l?-?1 there are at least k prime numbers.
Find and print the required minimum l. If no value l meets the described limitations, print -1.
Input
A single line contains three space-separated integers a, b, k (1 ≤ a, b, k ≤ 106; a ≤ b).
Output
In a single line print a single integer — the required minimum l. If there's no solution, print -1.
Examples
Input
2 4 2
Output
3
Input
6 13 1
Output
4
Input
1 4 3
Output
-1
題意:給出 a、b、k 三個數(shù),要求在區(qū)間 [a,b] 中找一個長度 l,使得對區(qū)間中任意一個位置到這個位置加上 l 后的子區(qū)間中存在 k 個質(zhì)數(shù),求最小的長度 l
思路:
首先用素數(shù)篩打一個素數(shù)表
由于 a、b 的數(shù)據(jù)范圍可達 1E6,單純的暴力一定會 TLE,而題目的關(guān)鍵是要求一個最小的長度,那么可以使用二分去枚舉長度,找一個最小的解
需要注意的是,如果單純使用素數(shù)表進行統(tǒng)計的話,依然會 TLE,需要考慮對素數(shù)表做出優(yōu)化,求一個素數(shù)表的前綴和,用于計算第 i 個數(shù)前有多少個素數(shù)
Source Program
#include<iostream> #include<cstdio> #include<cstdlib> #include<string> #include<cstring> #include<cmath> #include<ctime> #include<algorithm> #include<utility> #include<stack> #include<queue> #include<vector> #include<set> #include<map> #include<bitset> #define EPS 1e-9 #define PI acos(-1.0) #define INF 0x3f3f3f3f #define LL long long const int MOD = 1E9+7; const int N = 1000000+5; const int dx[] = {-1,1,0,0,-1,-1,1,1}; const int dy[] = {0,0,-1,1,-1,1,-1,1}; using namespace std;int prime[N],cnt; bool bprime[N]; int sum[N]; void make_prime() {memset(bprime,false,sizeof(bprime));bprime[0]=true;bprime[1]=true;for(int i=2;i<N;i++){if(!bprime[i]){prime[cnt++]=i;for(int j=i*2;j<N;j+=i){bprime[j]=true;}}} }bool judge(int a,int b,int k,int x) {for(int i=a;i<=b-x+1;i++)if(sum[i+x-1]-sum[i-1]<k)return false;return true; } int main() {make_prime();for(int i=1;i<=N;i++) {sum[i]=sum[i-1];if(!bprime[i])sum[i]++;}int a,b,k;scanf("%d%d%d",&a,&b,&k);int res=INF;int left=1,right=b-a+1;while(left<right){int mid=(left+right)/2;if(judge(a,b,k,mid))right=mid;elseleft=mid+1;}if(judge(a,b,k,left))printf("%d\n",left);elseprintf("-1\n");return 0; }?
總結(jié)
以上是生活随笔為你收集整理的Primes on Interval(CF-237C)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Little Elephant and
- 下一篇: 图论 —— 网络流 —— 费用流 ——