Prime Ring Problem HDU-1016

做题链接
在这里插入图片描述
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.

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,要构成一个素数环,这个素数由1-n组成,它的特征是选中环上的任意一个数字i,i与它相连的两个数加起来都分别为素数,满足就输出。
要全部搜索,所以用dfs,要判断是否是素数,并且看到数据最大是40.打表把1到40判断素数的结果存在数组里就最简单

#include<stdio.h>
#include<string.h>
int n;
int book[42];
int ans[44];//把符合条件的数字依次存入这个数组中
int pri[50]={0};//以空间换时间来判断数组
void prime(){//
	int i,j;
	
	for(i=0;i<50;i++)
		pri[i]=1;
	
	pri[0]=pri[1]=0;
	
	//下标值是素数的,其值为1,否则为0
	for(i=2;i<=7;i++)
		if(pri[i])
			for(j=2*i;j<100;j+=i)
				pri[j]=0;
}

void dfs(int count){
	//已经到最后一个数,并判断最后一个数与第一个数1相加是否为素数
	if(count==n&&pri[ans[count-1]+ans[0]]){
		//最后一个数字后没有空格
		for(int i=0;i<n-1;i++)
			printf("%d ",ans[i]);
		printf("%d\n",ans[n-1]);
		return ;
	}
	else{
		for(int i=1;i<=n;i++){
			//判断前面是否标记过以及该数与前面一个数之和是否为素数
			if(book[i]==0&&pri[i+ans[count-1]]){
				book[i]=1;
				ans[count]=i;
				dfs(count+1);
				book[i]=0;
			}
		}
	}
	return ;
}
int main(){
	
	prime();
	int i=0;
	while(scanf("%d",&n)==1){
		memset(book,0,sizeof(book));//初始化用于标记的数组
		memset(ans,0,sizeof(ans));//这一步要不要都行,不影响对错
		ans[0]=1;
		book[1]=1;
		printf("Case %d:\n",++i);
		dfs(1);
		printf("\n");
	}
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值