您的位置:首页 > 其它

Prime Ring Problem 素数环问题

2015-05-25 22:52 330 查看


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


题意不难理解,即一个环,由1~n组成,任意相邻的两个数之和为素数

主要是代码方面,原以为写了很多dfs这方面的代码,但是这次写仍然遇到了问题:

1.dfs里自己写的很乱

2.不够优化,比如判断素数时,想到了素数打表,但没想到用0,1代表是否为素数,下标代表这个数。

3.还可以更优化—n为奇数的时候不可能形成素数环,此处优化下面代码中未体现

附代码如下

#include<stdio.h>
#include<string.h>
int is_prime[]= {0,1,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},n;
int visited[21],a[21];
int flog;
void dfs(int step)
{
if(step==n&&is_prime[a[n-1]+1])
{
flog=0;
for(int i=0; i<n-1; i++)
printf("%d ",a[i]);
printf("%d\n",a[n-1]);
return;
}
for(int i=2; i<=n; i++)
{
if(visited[i]==0)
{
if(is_prime[a[step-1]+i])
{
visited[i]=1;
a[step++]=i;
dfs(step);
visited[i]=0;
step--;//写的时候把这条语句没写,汗···
}
}
}
}
int main()
{
int j=1;
while(~scanf("%d",&n))
{
flog=1;
printf("Case %d:\n",j++);
memset(visited,0,sizeof(visited));
a[0]=1;
dfs(1);
if(flog==1)
printf("No Answer\n");

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: