# Prime Ring Problem hdu 1016

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

68

Sample Output

Case 1:1 4 3 2 5 61 6 5 2 3 4Case 2:1 2 3 8 5 6 7 41 2 5 8 3 4 7 61 4 7 6 5 8 3 21 6 7 4 3 8 5 2

```#include <algorithm>

#include <cstring>
#include <iostream>
using namespace std;
int prime[50],book[50];
int ans[50],n;
void pri()//筛选素数 还有更快的改进版本，有兴趣可以百度
{
prime[0]=prime[1]=0; prime[2]=1;
for(int i=2;i<=50;i++)
{
for(int j=i*i;j<=50;j+=i)
prime[j]=0;
}
}
void dfs(int in)
{
if(in==n&&prime[ans[0]+ans[n-1]])
{
for(int i=0;i<n-1;i++)
printf("%d ",ans[i]);
printf("%d\n",ans[n-1]);
return ;
}else
{
for(int i=1;i<=n;i++)
if(!book[i]&&prime[i+ans[in-1]])
{
book[i]=1;
ans[in]=i;
dfs(in+1);
book[i]=0;

}

}
}
int main()
{
int cnt=1;
fill(prime,prime+50,1);
pri();
while(cin>>n)
{
memset(ans,0,sizeof(ans));
memset(book,0,sizeof(book));
ans[0]=1;
book[1]=1;
printf("Case %d:\n",cnt++);
dfs(1);
printf("\n");
}
return 0;
}            ```

309 篇文章26 人订阅

0 条评论