日常刷水题
在递归函数传x参数,是已经有多少个数填到序列里,最后判断下x是否等于总数n且序列首元素与序列末尾元素之和是否为素数,若都满足则输出序列,另外在进行搜索之前,与处理一下2~n*2范围内那些数为质数,这样就不用每次递归判断一次了,快些…
代码如下:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int n;
int ha[20];
bool pd[20];
bool pri[20];
int read()
{
char ch;
int data = 0;
int f = 1;
while(ch <'0'||ch >'9')
{
ch = getchar();
if(ch == '-')
f = -1;
}
do{
data = data*10 + ch-'0';
ch = getchar();
}while(ch >='0'&&ch <='9');
return data*f;
}
bool prime(int x)
{
for(int i = 2;i*i <= x;i++)
{
if(x%i==0&&x!=i)
{
return false;
}
}
return true;
}
inline void dfs(int x)
{
if(x == n&&pri[ha[0]+ha[n-1]])
{
for(int i = 0;i <= n-1;i++)
{
printf("%d ",ha[i]);
}
printf("\n");
}
for(int i = 2;i <= n;i++)
{
if(!pd[i]&&pri[i+ha[x-1]])
{
pd[i] = 1;
ha[x] = i;
// cout<<ha[x]<<endl;
dfs(x+1);
pd[i] = 0;
}
}
}
int main()
{
n = read();
for(int i = 2;i <= n*2;i++)
{
if(prime(i))
{
pri[i] = 1;
// cout<<i<<" yoooooooo: "<<pri[i]<<endl;
}
}
ha[0] = 1;
//cout<<"ha[0]:"<<ha[0]<<endl; hello world~
dfs(1);
return 0;
}
/*
样例1
6
1 4 3 2 5 6
1 6 5 2 3 4
*/
THE END
By Peacefuldoge