Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 3433 Accepted Submission(s): 1520
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.
![](http://acm.hdu.edu.cn/data/images/1016-1.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
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<iostream>
#include<stdio.h>
int g[50],a[30],b[30],n;
using namespace std;
void sous(int k,int m)
{
a[k]=m;
if(k==n)
{
if(g[1+m]==0)
return ;
printf("%d",a[1]);
for(int i=2;i<=n;i++)
printf(" %d",a[i]);
printf("\n");
return ;
}
for(int i=2;i<=n;i++)
if(b[i]&&g[i+m])
{
b[i]=0;
sous(k+1,i);
b[i]=1;
}
}
int main()
{
int i,j,k=1;
for(i=0;i<42;i++)
g[i]=0;
g[2]=g[3]=g[5]=g[7]=g[11]=g[13]=g[17]=g[19]=g[23]=g[29]=g[31]=g[37]=g[41]=1;
while(cin>>n)
{
for(i=0;i<=n;i++)
b[i]=1;
printf("Case %d:\n",k++);
sous(1,1);
printf("\n");
}
return 0;
}