您的位置:首页 > 其它

UVA - 524:Prime Ring Problem

2017-08-26 23:25 344 查看
A ring is composed of n (even number) circles as shown in diagram. Put natural numbers 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<=16)
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.
You are to write a program that completes above process.
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

Sample Code
#include<cstdio>
int prime[]={2,3,5,7,11,13,17,19,23,29,31,37};
int arr[20],vis[20];
int n;

bool is_prime(int num)
{
for(int i=0;i<12;i++)
if(prime[i]==num)return true;
return false;
}
void dfs(int cur)
{
if(cur==n && is_prime(arr[0]+arr[n-1]))
{
for(int i=0;i<n;i++)
printf("%d%c",arr[i],i==n-1?'\n':' ');
}
else for(int i=2;i<=n;i++)
{
if(!vis[i] && is_prime(i+arr[cur-1]))
{
arr[cur]=i;
vis[i]=1;
dfs(cur+1);
vis[i]=0;
}
}
}
int main()
{
int cnt=0;
while(scanf("%d",&n)!=EOF)
{
if(cnt)printf("\n");
printf("Case %d:\n",++cnt);
arr[0]=1;
dfs(1);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: