Codeforces 937B Vile Grasshoppers

本文介绍了一道有趣的算法题目,玩家需要找到一棵松树上最高的一个没有被草蜢占据的枝条。草蜢们占据从2到p编号的枝条,并能够跳跃到特定的枝条。文章提供了解题思路及AC代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The weather is fine today and hence it's high time to climb the nearby pine and enjoy the landscape.

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.

Input

The only line contains two integers p and y (2 ≤ p ≤ y ≤ 109).

Output

Output the number of the highest suitable branch. If there are none, print -1 instead.

Examples
Input
Copy
3 6
Output
5
Input
Copy
3 4
Output
-1
Note

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值