hdu 1016 Prime Ring Problem(dfs)
2015-09-01 18:01
393 查看
Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 34799 Accepted Submission(s): 15411
[align=left]Problem Description[/align]
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.
![](http://acm.hdu.edu.cn/data/images/1016-1.gif)
[align=left]Input[/align]
n (0 < n < 20).
[align=left]Output[/align]
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.
[align=left]Sample Input[/align]
6
8
[align=left]Sample Output[/align]
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
[align=left]Source[/align]
Asia 1996, Shanghai (Mainland China)
[align=left]Recommend[/align]
JGShining | We have carefully selected several similar problems for you: 1072 1372 1015 1258 1180
这是我第一道接触的搜索题,当时参考学长的代码写,却始终不能理解代码的意思,于是就一遍一遍第敲,直到整个代码都背下来了,后来接触的搜索逐渐增加,终于理解了这道题的代码,每次看到这道题,就能想起当年苦逼的敲代码。。。
题意:输入一个数n,代表从1到n个数,排序排成一个环,使得相邻两个数之和为素数(第一个和最后一个数也要满足),如果有多组情况,必须按从小到大的顺序输出,
附上代码:
#include <iostream> using namespace std; int a[30]= {0,1},b[30],sushu[50],n; //a表示素数环中的数字,b用来标记,sushu标记是否是素数 void DFS(int s,int k) //s代表当前循环到第几个数,k标记此时是否是第一次进人深搜函数 { int i,j; if(s>n) { if(sushu[a[1]+a ]) //最后一个数字和第一个数字的和 { for(i=1; i<=n; i++) //全部满足,输出这组数据的全部数 { if(i>1) cout<<" "; cout<<a[i]; } cout<<endl; } else return; //若最后一组数据不满足,则返回上一次循环 } for(i=2; i<=n; i++) { if(k) for(j=1; j<30; j++) //第一次进来,所有的数字都可以使用 b[j]=1; if(sushu[i+a[s-1]]&&b[i]) //i表示当前数字,a[s-1]表示上一个数字。两个数字之和为素数,且没有出现过i这个数字 { a[s]=i; //s位置上的数字记录为i b[i]=0; //0表示为已使用 DFS(s+1,0); //一个满足条件,进入下一个数字的选择 b[i]=1; //若返回上一层循环,标记已使用了的数字必须还原为未使用 } } } int main() { int i,j,t=1; for(i=0; i<50; i++) sushu[i]=1; sushu[0]=sushu[1]=0; for(i=2; i<=25; i++) if(sushu[i]) for(j=i+i; j<50; j+=i) sushu[j]=0; //素数打表,减少代码运行时间,素数为1,非素数为0 while(cin>>n) { cout<<"Case "<<t++<<":"<<endl; DFS(2,1); cout<<endl; } return 0; }
相关文章推荐
- leetcode 1: Two Sum
- 保護你的隱私,從 PGP 開始!
- SSDB主从配置
- android设计值得收藏的网站
- HDU4135-Co-prime-数论(容斥原理-模板)
- poj 2728 Desert King 【最优比例生成树 0-1分数规划】 【二分 or 迭代 + MST】
- springMVC 的实现
- 创业的第三十天
- Objective-C( Foundation框架 一 数组(NSArray))
- 使用blend改变图片颜色
- java死锁样例
- cocos2dlua-创建一个游戏
- hibernate查询缓慢问题(慎用排序等功能)
- 关于MySQL的SLEEP(N)函数
- easyui+nodejs+sqlserver增删改查实现
- windows下多个tomcat配置
- Eclipse 插件开发 向导
- 71.自动检测iOS网络并可跳转至设置界面设置网络
- getopt()函数 -- Linux
- Eclipse 插件开发遇到问题心得总结