题目链接:Prime Ring Problem
题目:
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.
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.
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
题意:
就是让你输入一个数n,然后从1-n这n个数,依次逆时针摆放,形成一个圆(如上图所示)。要求,任意相邻的两个数相加起来的和一定为素数;注意:第一个数从1开始;
AC代码:
#include <bits/stdc++.h>
using namespace std;
int n,ans=1;
int p[22];//将合适的结果记录下来
bool vist[22];//标记数组;
bool check(int a) //检查相邻两个数加起来是否为素数
{
if(a<=1) return false;
for(int i=2;i*i<=a;i++)
{
if(a%i==0)
return false;
}
return true;
}
void dfs(int x)
{
if(x==n&&check(1+p[n]))//当最后一个圈中放第n个数字时,并且这第n个数字能满足和第一个数字相加为素数就是符合条件
{
for(int i=1;i<=n;i++)
{
if(i==1) cout <<p[i];
else {
cout <<" "<<p[i];
}
}
cout <<endl;
return ;
}
for(int i=2;i<=n;i++)
{
if(check(i+p[x])&&!vist[i])//检测从2-n的每一个数是否符合条件
{
p[x+1]=i;//如果符合条件,则让存放数组的下一个地方存放该数字
vist[i]=true;//把该数字进行标记
dfs(x+1);//进行下一次的dfs
vist[i]=false;//恢复标记,回溯
}
}
}
int main()
{
while(cin >>n)
{
memset(p,0,sizeof(p));
memset(vist,false,sizeof(vist));
p[1]=1; //第一个数一定是1,所以直接存放
cout <<"Case "<<ans++<<":"<<endl;
dfs(1);//从1开始进行dfs
cout <<endl;
}
return 0;
}