HDOJ-1016 Prime Ring Problem

Prime Ring Problem

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


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
 
 1 // 1:当n为奇数的时候, 肯定没有符合条件的:2:符合条件的排列相邻的数字的奇偶性肯定不同;
 2 
 3 #include<stdio.h>
 4 #include<string.h>
 5 
 6 int used[20],prime[40],path[20];
 7 void DFS(int num,int n)
 8 {
 9     int i;
10     if(num>n&&prime[path[n]+path[1]])//判断第一个和最后一个数是否匹配
11     {
12         for(i=0;i<n;++i)
13             printf(i?" %d":"%d",path[i+1]);
14         printf("\n");
15         return;
16     }
17     for(i=2;i<=n;++i)//生成开头数字为1的所有排列
18     {
19         if(!used[i]&&prime[path[num-1]+i])//如果相邻两个数的和为素数,继续 
20         {
21             used[i]=1;//将i标记为已用;
22             path[num]=i;
23             DFS(num+1,n);
24             used[i]=0;//恢复原始状态
25         }
26     }
27 }
28 
29 int main()
30 {
31     int n,num=1;
32     prime[2]=prime[3]=prime[5]=prime[7]=prime[11]=prime[13]=prime[17]=prime[19]=
33     prime[23]=prime[29]=prime[31]=prime[37]=1;
34     path[1]=1;
35     while(scanf("%d",&n)!=EOF)
36     {
37         printf("Case %d:\n",num++);
38         if(n%2==0)//当n为奇数时,肯定不符合条件;
39         {
40             memset(used,0,sizeof(used));
41             DFS(2,n);//从第二个数开始搜索
42         }
43         printf("\n");
44     }
45 }

 

转载于:https://www.cnblogs.com/dongsheng/archive/2012/06/11/2545673.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值