# Prime Ring Problem
**Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 37427 Accepted Submission(s): 16521**
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.
![](https://box.kancloud.cn/2016-03-02_56d657ead445a.gif)
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.自然数(natural number),是非负整数(1, 2, 3, 4……)。认为自然数不包含[零](http://baike.baidu.com/subview/45676/8420704.htm)的其中一个理由是因为人们在开始学习数字的时候是由“一、二、三...”开始,而不是由“零、一、二、三...”开始, 因为这样是非常不自然的。在全球范围内,目前针对0是否属于自然数的争论依旧存在。在中国大陆,2000年左右之前的中小学教材一般不将0列入自然数之内,或称其属于“扩大的自然数列”。在2000年左右之后的新版中小学教材中,普遍将0列入自然数。
2.代码:
~~~
#include<cstdio>
#include<cstring>
using namespace std;
int n;
int vis[30];
int a[30];
int p[20]={2,3,5,7,11,13,17,19,23,29,31,37,41};
int c=1;
int cnt;
bool isPrime(int x)
{
for(int i=0;i<13;i++)
{
if(x==p[i])
{
return 1;
}
}
return 0;
}
void dfs(int level,int num)
{
a[level]=num;
vis[num]=1;
if(level==n)
{
if(isPrime(a[n]+a[1]))
{
if(cnt==0)
printf("Case %d:\n",c++);
cnt++;
for(int i=1;i<=n;i++)
{
if(i==1)
printf("%d",a[i]);
else
printf(" %d",a[i]);
}
printf("\n");
}
return;
}
for(int i=1;i<=n;i++)
{
if(vis[i]==1||isPrime(i+a[level])==0)
continue;
dfs(++level,i);
level--;
vis[i]=0;
}
}
int main()
{
while(scanf("%d",&n)==1)
{
memset(vis,0,sizeof(vis));
cnt=0;
dfs(1,1);
printf("\n");
}
return 0;
}
~~~
- 前言
- The 12th Zhejiang Provincial Collegiate Programming Contest - D
- 用邻接表存储n个顶点m条弧的有向图
- hdu 5289 Assignment(给一个数组,求有多少个区间,满足区间内的最大值和最小值之差小于k)
- hdu 1358 Period(给定一个字符串,求有多少个前缀(包括自己本身),它是由k(k&gt;2,并且尽量大)个循环节组成的)
- hdu 1806 Frequent values(给定一个非降序数组,求任意区间内出现次数最多的数的次数)
- poj 3264 Balanced Lineup(查询区间最大值与最小值的差)
- HDU 1010 Tempter of the Bone(DFS+奇偶剪枝)
- HDU 1015 Safecracker(第一次用了搜索去遍历超时,第二次用for循环可以了,思路一样的)
- HDU 1016 Prime Ring Problem(DFS)
- HDU 1026 Ignatius and the Princess I(BFS+记录路径)
- HDU 1072 Nightmare(BFS)
- HDU 1237 简单计算器(后缀式+栈)