HDU1016 Prime Ring Problem

Prime Ring Problem

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 28668    Accepted Submission(s): 12753


Problem 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.

HDU1016 Prime Ring Problem_第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
 

Source
Asia 1996, Shanghai (Mainland China)
 
思路:首先对【1,n】之间的数进行深搜,这就相当于放扑克牌的意思,然后用一个数【j从0开始计数,当然也可以从其他的数,不过末值要变。】标记a[i]+a[I+1]是素数的次数,当次数满足n-1时输出一种情况,(因为i最大为n-1);
代码:
#include<stdio.h>
int a[20];             //n>0&&n<20;
int book[20];           //标记;
int n;
int fun(int x)           用来判断一个数是否是素数;
{
	int i;
	for(i=2;i<x;i++)
	{
		if(x%i==0)
		{
			return 0;          //如果不是,返回0;
		}
	}
	return 1;                         //如果是素数,返回1;
}


void dfs(int step)                            //开搜:
{
	int i;
	if(step>2)                               //需要判断一下step是否大于2;因为i从2开始。如果不判断;step-2可能为0,出现问题;
	{
		if(fun(a[step-1]+a[step-2])==0)     //不满足,返回;
			return ;
	}
	if(step==n+1)                                     //如果值到达n,进行判断;
	{
		int j=0;
		for(i=1;i<n;i++)                          
		{
			if(fun(a[i]+a[i+1])==1)               //如果相邻的两个数相加是素数;j++;
				j++;
		}
			if(j==(n-1)&&fun(a[1]+a[n])==1)           //如果j达到n-1(因为j从0 开始的),并且a【1】和啊【n】的和也是素数,(因为是环状嘛)
			{                                                     //开始输出。
		       printf("%d",a[1]);
	           for(i=2;i<=n;i++)
			   {
		         printf(" %d",a[i]);
			   }
	              printf("\n");
			}
		         return ;
	}
	for(i=2;i<=n;i++)                              //这里相当于放扑克牌的搜法;


	{
		if(book[i]==0)
		{
			a[step]=i;
			book[i]=1;
			dfs(step+1);
			book[i]=0;
		}
	}
	return ;
}
int main()                                        //主函数
{
	int k=1;                                        //用来输出第几组数据;
	while(scanf("%d",&n)!=EOF)
	{
		a[1]=1;
		int i;
		for(i=1;i<=n;i++)
		{
			book[i]=0;
		}
		printf("Case %d:\n",k);
		dfs(2);
		k++;
		printf("\n");                     //数据之间空行隔了两行;
	}
	return 0;
}


[ Copy to Clipboard ]     [ Save to File]

你可能感兴趣的:(搜索DFS)