1031 质数环

1031 质数环

 

时间限制: 1 s
空间限制: 128000 KB
题目等级 : 黄金 Gold
 
 
 
 
题目描述 Description

一个大小为N(N<=17)的质数环是由1到N共N个自然数组成的一个数环,数环上每两个相邻的数字之和为质数。如下图是一个大小为6的质数环。为了方便描述,规定数环上的第一个数字总是1。如下图可用1 4 3 2 5 6来描述。若两个质数环,数字排列顺序相同则视为本质相同。现在要求你求出所有本质不同的数环。

输入描述 Input Description


只有一个数N,表示需求的质数环的大小。如:

输出描述 Output Description

每一行描述一个数环,如果有多组解,按照字典序从小到大输出。如:

样例输入 Sample Input

6

样例输出 Sample Output

1 4 3 2 5 6

1 6 5 2 3 4

数据范围及提示 Data Size & Hint
n<=17
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cmath>
 4 using namespace std;
 5 const int N=18;
 6 int n;
 7 int vis[N];
 8 int ans[N];
 9 int top;
10 int use[N];
11 void print()
12 {
13     for(int i=1;i<=n;i++)
14      {
15          printf("%d ",ans[i]);
16      }
17      printf("
");
18 }
19 bool pd(int l) 
20 {
21     for(int i=2; i<=sqrt(l); i++)
22         if(l%i==0)return false;
23     return true;
24 }
25 void dfs(int x)
26 {
27     for(int i=2;i<=n;i++)
28      {
29          if(use[i]==0&&pd(ans[x-1]+i))
30           {
31               ans[x]=i;
32               use[i]=1;
33               if(x==n&&pd(ans[n]+ans[1]))print();
34             else dfs(x+1);
35             use[i]=0;
36           }
37      } 
38 }
39 int main()
40 {
41     cin>>n;
42     if(n%2==1) 
43     {
44         cout<<endl;
45         return 0;
46     }
47     ans[1]=1;
48     dfs(2);
49 }
原文地址:https://www.cnblogs.com/lyqlyq/p/6752731.html