HDOJ-1016 Prime Ring Problem 素数环 DFS
2016-02-27 15:26
351 查看
Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others)Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 27754 Accepted Submission(s): 12338
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.
![](http://www.2cto.com/uploadfile/Collfiles/20141101/20141101084411330.gif)
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.
题意:找出一个数字环,使相邻的两个数字和为质数。注意输出时要打出一个空行。
#include <iostream> using namespace std; int n,res[25]; bool isok[25]; bool prime(int num) { for(int i=2;i<=sqrt(num+0.0);i++) if(num%i==0) return false; return true; } void dfs(int cur) { if((cur==n)&&prime(res[n-1]+1)) { for(int i=0;i<n-1;i++) cout<<res[i]<<" "; cout<<res[n-1]<<endl; return; } if(cur==0) { res[0]=1; isok[1]=true; dfs(cur+1); } else { for(int i=1;i<=n;i++) { if(!isok[i]&&prime(i+res[cur-1])) { isok[i]=true; res[cur]=i; dfs(cur+1); isok[i]=false; } } } } int main() { int cnt=1; while(cin>>n) { cout<<"Case "<<cnt++<<":"<<endl; for(int i=0;i<25;i++) isok[i]=false; dfs(0); cout<<endl; } }
这是我写的第一个搜索程序,写完挺激动←_←
相关文章推荐
- 004_Http之response响应头-01重定向
- EasyMonkeyDevice vs MonkeyDevice&HierarchyViewer API Mapping Matrix
- 使用Dmitry Sklyarov的方法来破解一款流行的4G调制解调器
- Leetcode problem 4:Median of Two Sorted Arrays
- android 仿nice实现在图片上打标签
- Android Fragment 生命周期图
- Python——异常编码细节
- C语言 指向结构体变量的指针
- bat文件编写(无线承载网络设置)
- 计算机工作的进行
- 第二天:图像标签及超链接的使用
- 译:在ASP.NET MVC5中如何使用Apache log4net 类库来记录日志
- JSP学习笔记三之response对象和request对象
- Ulua_toLua_基本案例(三)_CallLuaFunction
- 大型网站架构系列:分布式消息队列(一)
- Objective-C(1) 认识一下吧
- 学习Kotlin笔记记录。--------类
- Mariadb/mysql使用技巧--持续更新
- 103. Binary Tree Zigzag Level Order Traversal
- Java在linux下调用C/C++生成的so文件