USACO Section 1.5 Superprime Rib - 构造数列

    这题直接来枚举再判断显然是效率很低的...我是采取构造的方法...首先将2,3,5,7入队列..然后每次从队头取出一个数..枚举再他后面加1~9后还是不是质数..是的话入队...

    当然从队头每次取出一个数后...判断下其位数~~若是等于要求的长度就直接输出了..并且因为构造的时候就保证了其顺序...所以输出顺序也会是满足要求的...

Program:

/*  
ID: zzyzzy12  
LANG: C++  
TASK: sprime
*/    
#include<iostream>    
#include<stdio.h>    
#include<string.h>    
#include<math.h>    
#include<algorithm>    
#include<queue>
using namespace std;    
int getlen(int a)
{
     int k=1,i=0;
     while (k<=a) {  k*=10;  i++; }
     return i;   
}
bool IsPrime(int a)
{
     int k;
     for (k=2;k<=a/k;k++) 
       if (a%k==0) return false;
     return true;
}
int h,p,i,n;
queue<int> myqueue;
int main()
{
     freopen("sprime.in","r",stdin);
     freopen("sprime.out","w",stdout);  
     scanf("%d",&n);
     while (!myqueue.empty()) myqueue.pop();
     myqueue.push(2);  myqueue.push(3);
     myqueue.push(5);  myqueue.push(7);
     while (!myqueue.empty())
     {
           h=myqueue.front();
           myqueue.pop();
           p=getlen(h);
           if (p==n)   
           {
                printf("%d\n",h);       
                continue;            
           }  
           for (i=1;i<=9;i+=2)
           if (IsPrime(h*10+i)) myqueue.push(h*10+i);
     }
     return 0;   
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值