您的位置:首页 > 其它

Prime Ring Problem

2014-02-23 17:20 155 查看
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


思路:典型的深搜题,思想看代码

#include<stdio.h>
#include<string.h>
using namespace std;
int a[20],vis[20],n;
int prime(int m)
{
int i;
for(i=2;i*i<=m;i++)
if(m%i==0) return 0;
return 1;
}//判断素数函数
int dsf(int step)
{
int i;
if(step==n+1&&prime(a
+a[1]))//递归结束的条件,不要忘记判断最后一个数和第一个数的和是否是素数
{
for(i=1;i<n;i++)
printf("%d ",a[i]);
printf("%d\n",a
);
return 0;
}
for(i=2;i<=n;i++)//题目要求从一开始,所以这里从二开始循环
{
if(!vis[i]&&prime(i+a[step-1]))//判断当前的数是否被用过,并且与上一个数的和是素数
{
a[step]=i;
vis[i]=1;//每用一次就标记上
dsf(step+1);调用递归函数
vis[i]=0;回溯的时候清零,以便下次用
}
}
}
int main()
{
int k=1;
a[1]=1;
while(scanf("%d",&n)!=EOF)
{
memset(vis,0,sizeof(vis));标记数组清零
printf("Case %d:\n",k++);
dsf(2);从二开始
printf("\n");
}
return 0;
}


虽然题很水,但还是做了很长时间,这就是菜鸟的世界,你不懂。。。。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: