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
Sponsor
本题输出的时候要注意格式问题,如果最后输出的数后有空格,则会出现格式错误。还有每一个样例结束要空出一行。
#include<stdio.h>
#include<string.h>
int b[30], book[30];
int T, count = 0;
int judge(int n)//素数判断
{
int i;
for (i = 2; i < n; i++)
{
if (n % i == 0)
return 0;
}
return 1;
}
void dfs(int n)
{
int i, j;
if (n == T && judge(b[n] + 1) == 1)//如果最后一个数和第一个数相加是素数
{
for (i = 1; i <= T; i++)
if (i == 1)
printf("%d", b[i]);
else
printf(" %d", b[i]);//最后不能输出空格,所以分开后 用 空格%d;
printf("\n");
}
if (n == T)
return;//当最后一个数加第一个数不是素数
for (i = 2; i <= T; i++)
{
if (judge(b[n] + i) == 1 && book[i] == 0)//当这两个数相加是素数并且这个数是第一次出现
{
book[i] = 1;//标记在这个数
b[n + 1] = i;//将其存入输出的数组中
dfs(n + 1);//接着深搜
book[i] = 0;//取消上一次标记
}
}
}
int main()
{
while (scanf("%d", &T) != EOF)
{
memset(book, 0, sizeof(book));
b[1] = 1;//让第一个数为1
book[1] = 1;//标记1已经出现
count++;
printf("Case %d:\n", count);
dfs(1);//从1开始深搜
printf("\n");
}
}