The pine's trunk includes several branches, located one above another and numbered from 2 to y. Some of them (more precise, from 2 to p) are occupied by tiny vile grasshoppers which you're at war with. These grasshoppers are known for their awesome jumping skills: the grasshopper at branch x can jump to branches .
Keeping this in mind, you wisely decided to choose such a branch that none of the grasshoppers could interrupt you. At the same time you wanna settle as high as possible since the view from up there is simply breathtaking.
In other words, your goal is to find the highest branch that cannot be reached by any of the grasshoppers or report that it's impossible.
The only line contains two integers p and y (2 ≤ p ≤ y ≤ 109).
Output the number of the highest suitable branch. If there are none, print -1 instead.
3 6
5
3 4
-1
In the first sample case grasshopper from branch 2 reaches branches 2, 4 and 6 while branch 3 is initially settled by another grasshopper. Therefore the answer is 5.
It immediately follows that there are no valid branches in second sample case.
题意:有一堆蚂蚱占据了树枝2~p的位置,然后这个树枝的最大高度为y,每一个蚂蚱都会跳到。然后问你,人想站在没有蚂蚱能碰到的地方,并且是最高的树枝编号,如果没有就输出-1
解题思路:一开始比赛的时候看这个蚂蚱跳的规律没看懂,看了下提示之后,我就隐约觉得有点需要素数筛的样子,整理一下思路之后,我觉得可以暴力从y开始枚举到p+1过?(1)如果不用素数筛的话,情况会怎么样?(2) 如果需要用到素数筛的话,你得一开始的时候筛到多少的范围过?(3)如果这个枚举的数X能被2~p里的素数给整除,就说明这个树枝是有蚂蚱能跳上去的,那么我们就枚举下一个树枝。重复这个过程,直到p+1。如果找到了就输出,没找到就输出-1.
请先思考这三个问题几分钟。
(1)不管是哪一种情况,你枚举的树枝X一定要么很快的就被素数给整除,要么就是正确答案,寻找的时间一定不长
(2)如果不用素数筛的话,有些操作是重复的,不需要进行的,这就有可能造成超时
(3)因为这个数据范围到了1e9所以我们得筛到1e5的素数(感谢大佬的提点)
最后附上我的AC代码
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<map>
using namespace std;
#define MAX 100000
long long su[MAX],cnt;
bool isprime[MAX];
long long p,y;
void prime(){
cnt=1;
memset(isprime,1,sizeof(isprime));
isprime[0]=isprime[1]=0;
for(long long i=2;i<=MAX;i++){
if(isprime[i])
su[cnt++]=i;
for(long long j=1;j<cnt&&su[j]*i<MAX;j++){
isprime[su[j]*i]=0;
}
}
}
int main(){
long long i,j;
scanf("%I64d%I64d",&p,&y);
prime();
long long n=y;
while(n>p){
int flag=1;
for(i=1;i<cnt&&su[i]<=p;i++){
if(n%su[i]==0){
flag=0;
break;
}
}
if(flag==1){
break;
}
n--;
}
if(n<=p)
printf("-1\n");
else
printf("%I64d\n",n);
return 0;
}