题目:http://www.acmore.net/problem.php?cid=1013&pid=5
#include <iostream> #include <stdio.h> #include <string> #include <string.h> #include <algorithm> #include <math.h> #include <fstream> #include <vector> #include <map> #include <queue> #include <stack> #include <math.h> #include <stdlib.h> using namespace std ; const int maxn=10008; int prime[maxn]; int isprime[maxn]; int id,a_id; int ans[maxn]; void make_prime(){ memset(isprime,0,sizeof(isprime)); id = 0; for(int i = 2;i < maxn;i++){ if(!isprime[i]) prime[id++] = i; for(int j = i+i;j < maxn;j+=i) if(!isprime[j]) isprime[j] = 1; } //for(int i = 0;i < 1000;i++) // printf("%d ",prime[i]); } bool check_isprime(int x){ int temp = sqrt(x+0.5); for(int i = 0;i < id&&prime[i]<=temp;i++){ if(x%prime[i] == 0) return 0; } return 1; } struct node{ int num; int len; node(){} node(int n,int l):num(n),len(l){}; }; void bfs(int len){ queue<node>que; que.push(node(2,1)); que.push(node(3,1)); que.push(node(5,1)); que.push(node(7,1)); while(!que.empty()){ int temp,next; node now = que.front(); que.pop(); if(now.len == len){ ans[a_id++] = now.num; } else{ for(int i = 1;i < 10;i++){ next = 10*now.num + i; if(check_isprime(next)) que.push(node(next,now.len+1)); } } } } int main(){ int n; while(~scanf("%d",&n)){ make_prime(); a_id = 0; bfs(n); for(int i = 0;i < a_id;i++) printf("%d\n",ans[i]); } return 0 ; }