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.
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
8
Sample Output
Case 1:
1 4 3 2 5 6
1 6 5 2 3 4
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
这道题是输入n,让你找从1到n这些整数组成的 相邻的数的和为素数的环有几个,从1开始顺时针输出
注意题目要求输出一行Case n:(看清这个冒号啊~~~~~~~~当时没看到一直wr),而且Print a blank line after each case. ,(也没看清这个,真是惨啊~~~~)
减小复杂度的技巧:题中出现的最大素数为37,所以不必每种情况都再算一次相邻的数的和是不是素数,这样可能超时,而且dfs本来复杂度就挺高的,可以用pri[i]表记i是否为素数,
#include <cstdio>
#include <string.h>
#include <math.h>
int num[], t, n, now; //num记录最后选中的数
bool vis[], pri[];//pri[i] = 1表示i为素数,pri[i] = 0表示i不是素数
bool prime(int y) //bool类型的函数,这样就不用定义变量作为返回值了
{
for(int i = ; i <= sqrt(y); i++)
{
if(y % i == )
return false;
}
return true;
}
void dfs(int now, int t) //已经找到t个数了,第t个数为now,也就是当前数为now,进入dfs也就是找第t+1个数
{
if(t == n) //该找第n个数时,看看第n个数和第一个数相加是否是素数,因为组成的是个环,ps:一定记得!!!
{
if(pri[now+])
{
printf("");
for(int i = ; i <= n; i++)
printf(" %d", num[i]);
printf("\n");
}
return;
} for(int i = ; i <= n; i++)
{
if(vis[i] && pri[i+now])
{
vis[i] = ;
num[t+] = i;
dfs(i, t+);
vis[i] = ;
}
} }
int main()
{
int cnt = ;
while(~scanf("%d", &n))
{
memset(vis, , sizeof(vis));
for(int i = ; i < ; i++)
{
if(prime(i))
pri[i] = ;
else
pri[i] = ;
}
printf("Case %d:\n", cnt++); //当时忘了冒号!!!!!!!!!!!!!!!!!!!!!!!!!!惨啊~~~~
num[]=; vis[] = ;
dfs(, );
printf("\n");//当时也忘了每个案例之间也要输出空行~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~!!!!!!!!!!嗷~~~
}
return ;
}