题目:把1-n,连续的放到一个环里,使相邻的数字和为素数,输出所有结果。
思路:
这题一个性质进行剪枝:相邻的数字一定是奇偶性不同的数字。
(如果上述假设不成立,则存在相邻的奇数或偶数,那么他们的和一定是大于2的偶数,不是素数)
根据上面的假设,还有一条推论:只有n为偶数时才有解。
(n为奇数,一直至少有一对奇数或者一对偶数相邻,同上,矛盾(鸽巢原理))
当然简单的回溯也可以,如果n很大就需要上面的性质剪枝了
紫书原题
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn=50;
int n,isp[maxn],vis[maxn],a[maxn]={1};
void init(){
for(int i=2; i<50; i++)isp[i]=1;
for(int i=2; i<50; i++)
for(int j=2*i; j+i<50; j+=i)isp[j]=0;
}
void dfs(int cur){
if(cur == n && isp[a[0]+a[n-1]]){
for(int i=0; i<n; i++)printf("%d ",a[i]);
puts("");
}
else{
for(int i=2; i<=n; i++){
if(!vis[i] && isp[i+a[cur-1]]){
a[cur]=i;
vis[i]=1;
dfs(cur+1);
vis[i]=0;
}
}
}
}
int main(){
init();int kase=0;
while(~scanf("%d",&n)){
if(kase++)printf("\n");
printf("Case %d:\n",kase);
dfs(1);
}
return 0;
}