给定数n,在n的所有排列中,记a[1],a[2],...,a[n],求满足a[i]+a[i+1](1<=i<=n-1)是素数并且a[1]+a[n]也是素数的所有排列。排列按字典序输出。
#include<stdio.h>
#include<iostream>
using namespace std;
#define NO 20
bool prime[]={0,1,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0,0};
bool mark[NO];
int n;
int stack[NO],top;
void print()
{
printf("%d",stack[0]);
for(int i=1;i<top;i++)
printf(" %d",stack[i]);
puts("");
}
void dfs()
{
if(top==n)
{
if(prime[stack[0]+stack[top-1]])
print();
return;
}
int i;
for(i=2;i<=n;i++)
if(!mark[i]&&prime[stack[top-1]+i])
{
mark[i]=1;
stack[top++]=i;
dfs();
top--;
mark[i]=0;
}
}
int main()
{
while(~scanf("%d",&n))
{
mark[1]=1;
stack[top++]=1;
dfs();
}
return 0;
}