洛谷P1218 [USACO1.5]特殊的质数肋骨 Superprime Rib

题目描述 https://www.luogu.org/problemnew/show/P1218
我以为这个题也可以用埃氏筛法来做,但位数太大,boom,空间爆了。
其实就直接搜就行了,由题意能知道,这些数是不含有偶数的,第一位也一定是质数,这样能提高效率。

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
int n,a[5]={1,3,5,7,9};
bool jud(int x)
{
    if(x==1) return 0;
    if(x==2) return 1;
    for(int i=2;i<=sqrt(x);i++)
      if(x%i==0) return 0;
    return 1;
}
void dfs(int k,int now)
{
	if(now==n){ printf("%d\n",k); return;}
	else
	{
		for(int i=0;i<5;i++)
		{
			int p=k*10+a[i];
			if(jud(p)) dfs(p,now+1);
		}
	}
}
int main()
{  
   scanf("%d",&n);
   dfs(2,1);
   dfs(3,1);
   dfs(5,1);
   dfs(7,1);
	
  return 0;	
}

猜你喜欢

转载自blog.csdn.net/qq_42920122/article/details/88777914