素数环(深搜dfs)

 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

这道题其实也并不难,题意就是输入一个整数n,输出一个素数环,使每相邻的两个数相加都是一个素数。

#include
#include
#include
int a[20000],book[20000],n;
int prime(int c)
{
	int k,i;
	if(c==1)
	return 0;
	k=(int)sqrt(c);
	for(i=2;i<=k;i++)
		if(c%i==0)
			return 0;
	return 1;
}
void dfs(int s)
{
	int i,r=0;
	if(s==n&&prime(a[0]+a[n-1])==1)//这个地方别忘了判断首尾相加是否是素数
	{
		for(i=0;i<n;i++)
		{
			if(r==0)
			{
				r=1;
				printf("%d",a[i]);
			}
			else
				printf(" %d",a[i]);
		}
		printf("\n");
	}
	else
	{
		for(i=2;i<=n;i++)
		{
			if(book[i]==0&&prime(i+a[s-1])==1)//判断当前位置的数与前面一个
			//数相加之后的值是否为素数
			{
				book[i]=1;
				a[s]=i;
				dfs(s+1);
				book[i]=0;
			}
		}
	}
}
int main()
{
	int i,r=0;
	while(scanf("%d",&n)!=EOF)
	{
        memset(book,0,sizeof(book));//每次清零
        memset(a,0,sizeof(a));
		r++;
		a[0]=1;
		book[1]=1;
		printf("Case %d:\n",r);
		dfs(1);
		printf("\n");
	}
	return 0;
}

你可能感兴趣的:(个人经验)