您的位置:首页 > 其它

hdu 1016 Prime Ring Problem

2014-08-11 15:55 246 查看
参考博文:/article/4984202.html


Prime Ring Problem

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 26786 Accepted Submission(s): 11950



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


Source

Asia 1996, Shanghai (Mainland China)

这题的思路就写在代码里了。刚看到题时,要说什么想法都没有还是有一点儿的,但又不知从何入手,所以参考了前辈的代码,相应的原文链接就在文首,代码也几乎是复制版本(先仔细推敲前辈的代码,开启记忆功能,然后自己一点儿点儿的近乎默写的形式敲出了几乎全部代码,测试时有问题又回头比照了原文。) 再注释一遍,权当复习,以后回头望时还有个痕迹~


参考代码:

#include<iostream>
#include<cstdio>
using namespace std;
int n;
int num[25]={0,1};                      //输出数组
int prime[20]={2,3,5,7,11,13,17,19,23,29,31,37};
//先把1-20范围内任意两数相加可能得到的质数罗列出来,供之后查证用
int mark[21];

void print()
{
int i;
for(i=1;i<n;i++)
printf("%d ",num[i]);
printf("%d\n",num[i]);
}

int isPrime(int x)                      //在所有可能的质数中找寻该数,方便查证该数是否为质数
{
int i;
for(i=0;i<12;i++)
{
if(x==prime[i])
return 1;
}
return 0;
}
int sear(int pre,int post,int flag)     //深搜函数,pre为前一个节点,post为当前节点,flag是节点序号
{
int i;
if(!isPrime(pre+post))              //若两数之和不为质数,直接退出
return 0;
num[flag]=post;                     //符合要求,将当前节点post保存到num数组对应位置中。
if(flag==n&&isPrime(post+1))        /*序号为n,即所有节点已经找全,且当前节点,即最末尾节点与头节点之和为质数,则打印该序列并返回1.*/
{
print();
return 1;
}
mark[post]=0;                       //已使用过的数字标记为0
for(i=2;i<=n;i++)
{
if(mark[i]!=0&&sear(post,i,flag+1)) //接下来是递归搜索在当前序列下的后续可能序列,到达底部后再层层返回
break;
}
mark[post]=1;                        //已使用数字的标记恢复为1
return 0;
}

int main()
{
int i;
int order=1;
while(~scanf("%d",&n))
{
printf("Case %d:\n",order++);
for(i=1;i<=n;i++)                //标记所有数字都可使用
mark[i]=1;
if(n==1)
printf("1\n");
for(i=2;i<=n;i++)                //头元素固定为1,第二元素从2开始到n变化,深度优先搜索
sear(1,i,2);
printf("\n");                    //案例末尾换行
}
return 0;
}



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: