大意:给出一个n,把前n个数填在这n个圈里形成一个环,使得相邻的圈中的数相加都为素数。
题目:
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 (0 < n < 20).
OutputThe 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 8Sample 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、要记得判断一下最后一个数和第一个数相加是否是素数。
2、因为这道题数据比较小,可以用数组来避免编写判断素数的函数(编了貌似也可以)
下面是代码:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
int n,a[22]={1},vis[22];
void print(int cur);
int is[40]={0,0,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0};
int main(void)
{
int k=0;
while(~scanf("%d",&n))
{
printf("Case %d:\n",++k);
memset(vis,0,sizeof(vis));
print(1);
printf("\n");
}
return 0;
}
void print(int cur)
{
int i;
if(cur==n&&is[a[0]+a[n-1]])
{
for(i=0;i<n;i++)
{
printf("%d%c",a[i],i==n-1?'\n':' ');
}
return;
}
else
{
for(i=2;i<=n;i++)
{
if(is[a[cur-1]+i]&&!vis[i])
{
a[cur]=i;
vis[i]=1;
print(cur+1);
vis[i]=0;
}
}
}
}