Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 20270 Accepted Submission(s): 9071
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
Source
Recommend
JGShining
#include<iostream>
using namespace std;
int isp[40]={0,0,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0};//40以内的素数表
int a[20]; int t;//a为最后输出数组,t为长度
int vis[20];//标记是否使用过这个数
void dfs(int cur)//从1开始,cur为位置,已知上一位置的值,找出这一位置的值
{
a[0]=1;//第一个位置默认为1
if(cur==t&&isp[a[0]+a[t-1]]==1)//如果位置到了最后一个,检测第一个位置上的值和最后一个位置上的值是否为素数
{
for(int i=0;i<t-1;i++)//输出每个位置上的值
cout<<a[i]<<' ';
cout<<a[t-1]<<endl;
}
else//如果还没到最后,则进行这个位置的找值
for(int i=2;i<=t;i++)//i指的是值,每个值都要试试是否符合这个位置
{
if(isp[a[cur-1]+i]==1&&vis[i]==0)//前一句,上一个位置的值和这个值相加为素数,后一句,这个值没被使用过
{
a[cur]=i;//符合以上条件,这个位置的值即为i
vis[i]=1;//标记这个值使用过
dfs(cur+1);//进行下一个位置值得搜索
vis[i]=0;//如果上一步退回,则说明这个值不可用,标记未被使用过
}
}
return ;//结束
}
int main()
{
int num=1;
while(cin>>t)//输入最大的值,或者说是最大位置
{
cout<<"Case "<<num<<':'<<endl;
memset(vis,0,sizeof(vis));//初始化皆没使用过
vis[1]=1;//数值1默认第一个,必使用过
dfs(1);//cur皆是在找这个位置的值
cout<<endl;
num++;
}
return 0;
}