524 Prime Ring Problem
A ring is composed of n (even number) circles as shown in diagram. Putnatural numbers 1; 2; : : : ; n into each circle separately, and the sum ofnumbers in two adjacent circles should be a prime.Note: the number of first circle should always be 1.Inputn (0 < n 16)OutputThe output format is shown as sample below. Each row represents a series of circle numbers in thering beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the aboverequirements.You are to write a program that completes above process.Sample Input68Sample OutputCase 1:1 4 3 2 5 61 6 5 2 3 4Case 2:1 2 3 8 5 6 7 41 2 5 8 3 4 7 61 4 7 6 5 8 3 21 6 7 4 3 8 5 2题意:
给出一个偶数N,需要将1到N这N个数等距排列在一个圆周上,使得相邻两个数的和总是一个素数,将所有的解(镜面对称的两个解视作不同解)都按顺时针顺序打印出来。
输入:
正整数N。
输出:
所有解。
分析:
使用深搜的方式进行枚举即可。从1开始打印解。
1 #include2 #include 3 #define MAX_N 50 4 using namespace std; 5 int n,A[MAX_N] = { 1},ispe[MAX_N],vis[MAX_N]; 6 void dfs(int cur){ 7 if(cur == n && ispe[A[0] + A[n - 1]]){ 8 for(int i = 0; i < n; i++) 9 i ? printf(" %d", A[i]) : printf("%d", A[i]);10 printf("\n");11 }else for(int i = 2; i <= n; i++)12 if(!vis[i]&& ispe[i + A[cur - 1]]){13 A[cur] = i;14 vis[i] = 1;15 dfs(cur + 1);16 vis[i] = 0;17 }18 }19 int main(){20 for(int i = 2; i <= 50; i++) ispe[i] = 1;21 for(int i = 2; i <= 50; i++)22 for(int j = i + i; j + i <= 50; j += i)23 ispe[j] = 0;24 int kase = 0;25 while(cin >> n){26 if(kase++)27 printf("\n");28 printf("Case %d:\n",kase);29 dfs(1);30 }31 return 0;32 }