Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 38929 Accepted Submission(s): 17184
Problem Description
A ring is compose of n circles as shown in diagram. Put natural number 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.

Note: the number of first circle should always be 1.

Input
n (0 < n < 20).
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. Print solutions in lexicographical order.
You are to write a program that completes above process.
Print a blank line after each case.
You are to write a program that completes above process.
Print a blank line after each case.
Sample Input
6 8
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【代码如下】#include <stdio.h> #include <iostream> #include <cstring>//memset #include<math.h> #include<algorithm> using namespace std; int n, kase = 0; int op[25]={0}, rightcope[25]={0}; int prime[45] = {0}; void dfs(int num, int pos)//num代表前一个位置,pos代表环正在确定的数字的位置 { if(pos == n && !prime[num+1])//已经成环,1是那个起始数字,即判断是否成环,而且最后一位和第一位(也就是1)之和是否是素数 { for(int i=0; i<n; i++) { if(i != 0) cout<<" "; cout<<rightcope[i]; }//进行输出 cout<<endl; } //如果不满足成环 //继续深搜 for(int i=1; i<=n; i++) { if(!op[i] && !prime[num+i])//找出还没有被占用的数字,并且它的前一位和它的和是素数 { op[i] = 1; rightcope[pos] = i; dfs(i, pos+1); op[i] = 0;//回溯,dfs进行结束后进行; } } } int main() { for(int i=2;i<22;i++)//筛选法打表,素数用0标记 for(int j=i+i;j<45;j+=i) prime[j]=1; while(scanf("%d", &n)!= EOF) { printf("Case %d:\n", ++kase); // memset(op, 0, sizeof(op));//op[]记录数字是否被占用 //memset(rightcope, 0, sizeof(rightcope));//rightcope记录环的第一个位置 op[1] = 1;//数字1被占用 rightcope[0] = 1;//刚开始环从第一个位置开始 dfs(1,1);//对下一位应该填什么进行深搜 cout<<endl; } }