洛谷P7960 [NOIP2021] 报数 (筛法)

2022/6/17 23:28:22

本文主要是介绍洛谷P7960 [NOIP2021] 报数 (筛法),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

禁止报的数的生成规则与埃式筛法类似,考虑用筛法预处理可以报出的数字列表和不可报出的数字,从而 O(1) 回答每一组询问。

用check函数判断数字中是否含有7,用nx[i]记录数字i的下一个合法数。

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int N=1e7+10;
 4 int T,ls;
 5 int f[N],nx[N];
 6 
 7 bool check(int x){//判断是否含有数字7 
 8     while(x){
 9         if(x%10==7) return 1;
10         x/=10;
11     }
12     return 0;
13 }
14 
15 int read(){
16     int x=0,f=1;char c=getchar();
17     while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();}
18     while(c>='0'&&c<='9') x=(x<<3)+(x<<1)+(c^48),c=getchar();
19     return x*f;
20 }
21 
22 void init(){
23     for(int i=1;i<=N;i++){
24         if(f[i]) continue;
25         if(check(i)){
26             for(int j=i;j<=N;j+=i) f[j]=1;
27             continue;
28         }
29         nx[ls]=i;
30         ls=i;
31     }
32 }
33 
34 int main(){
35     init();//预处理 
36     T=read(); 
37     while(T--){
38         int x;
39         x=read();
40         if(f[x]) puts("-1");
41         else cout<<nx[x]<<endl;
42     }
43     return 0;
44 }

 



这篇关于洛谷P7960 [NOIP2021] 报数 (筛法)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程