# 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.

?
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 簡單計算器(后綴式+棧)