UVa524

524 Prime Ring Problem
A ring is composed of n (even number) circles as shown in diagram. Put
natural numbers 1; 2; : : : ; n into each circle separately, and the sum of
numbers in two adjacent circles should be a prime.
Note: the number of first circle should always be 1.
Input
n (0 < n  16)
Output
The output format is shown as sample below. Each row represents a series of circle numbers in the
ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above
requirements.
You are to write a program that completes above process.
Sample Input
68
Sample Output
Case 1:
1 4 3 2 5 6
1 6 5 2 3 4
Case 2:
1 2 3 8 5 6 7 4
1 2 5 8 3 4 7 6
1 4 7 6 5 8 3 2
1 6 7 4 3 8 5 2

题意:
       给出一个偶数N,需要将1到N这N个数等距排列在一个圆周上,使得相邻两个数的和总是一个素数,将所有的解(镜面对称的两个解视作不同解)都按顺时针顺序打印出来。

输入:

       正整数N。

输出:

       所有解。

分析:

使用深搜的方式进行枚举即可。从1开始打印解。

 1 #include<iostream>
 2 #include<cstdio>
 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("
");
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("
");
28         printf("Case %d:
",kase);
29         dfs(1);
30     }
31     return 0;
32 }
View Code
原文地址:https://www.cnblogs.com/cyb123456/p/5792815.html