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 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
思路:
回溯法,这个类似于“n皇后”问题。
这个算法用楼梯来形象的描述一下是:当你站在某阶时,判断是否到地面(到地面就结束),不到地面,那么就考虑要下到(题目中限制的)第几阶,并且记录(book),最后归零
实现代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int n,a[50],book[50];/*这里的a对应输出的数*/
int prime(int x)/*判断素数,是素数返回1*/
{
for(int i=2;i*i<=x;i++)
{
if(x%i==0)return 0;
}
return 1;
}
void dfs(int y)
{
if(y==n&&prime(1+a[n-1])==1)/*判断环里面最后一个数和第一个数1的和是否为素数*/
{
printf("1");
for(int i=1;i<=n-1;i++)
{
printf(" %d",a[i]);
}
printf("\n");
}
for(int i=2;i<=n;i++)
{
if(!book[i]&&prime(a[y-1]+i)==1)
{
a[y]=i;
book[i]=1;
dfs(y+1);
book[i]=0;/*这里的最后归零很重要!!*/
}
}
}
int main()
{
int k=0;
while(~scanf("%d",&n))
{
printf("Case %d:\n",++k);
memset(book,0,sizeof(book));
a[0]=1;
dfs(1);
printf("\n"); /*格式需要*/
}
return 0;
}
注意:格式!刚开始阿久把 printf("\n"); /*格式需要*/ 放在了printf("Case %d:\n",++k);上面:写的是if(k>0)printf("\n");/*格式需要*/ 提交,Presentation Error 。所以注意格式呀Q.Q
补充:判断素数的函数(更高效)
int is_prime(int x)
{
for (int i = 2; i*i <= x; i++)
if (x % i == 0) return 0;
return 1;
}