HDU 1016 Prime Ring Problem
2016-03-16 21:28
531 查看
Prime Ring Problem
[b]Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 39008 Accepted Submission(s): 17213
[/b]
[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.
[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
题目大意:给定一个正整数n(0<n<20),然后将1-n排在一个圆环上面,要求每相邻的两个整数相加起来是素数。
思路:DFS+剪枝。用深搜求出所有的排列然后判断每一个排列是否满足题目要求。
如果不剪枝的话肯定要超时,事实证明也确实是这样,第一次不信邪没有简直提交果断超时,然后简单的剪了一下,AC了。
题目还是比较简单的,很容易理解,比之前做的HDU1010需要奇偶剪枝的容易了不知道多少倍~
然后还有一个要注意的地方是输出,每输出一个测试数据就换一下行,不是每两组测试数据之间换行,之前也因为这个表达错误了一次。
AC代码:
#include<iostream> #include<cstring> using namespace std; int cir[25], isFind[25];//isFind数组用来记录数是否已经被用过 bool isPrime(int n)//判断素数 { int i = 2; for (; i < n; i++) { if (n % i == 0) return 0; } return 1; } void dfs(int i, int n) { if (i >= n) { if (isPrime(cir[n-1] + cir[0]))// 最后判断最后一个数字和第一个数字的和是不是素数 for (int x = 0; x < n; x++) if(x != n -1) cout << cir[x] << " "; else cout << cir[x] << endl; } int j; for (j = 2; j <= n; j++) { if (isFind[j]) continue; cir[i] = j; isFind[j] = 1; if ( !isPrime(cir[i - 1] + cir[i]) ) //判断当前数与之前一个数的和是不是素数, 不是就直接pass, 也就是剪枝 { isFind[j] = 0;//如果不满足,就恢复数字的使用标记,进行下一次循环 continue; } dfs(i + 1, n); isFind[j] = 0;// 恢复数字的使用标记 } } int main() { int n, i, count = 0; while (cin >> n) { cout << "Case " << ++count << ":" << endl; memset(cir, 0, sizeof(cir)); memset(isFind, 0, sizeof(isFind)); cir[0] = 1;//题目规定第一个数字必须是1 dfs(1, n);//从i=1即第二个数字开始向下搜索 cout << endl; } return 0; }
相关文章推荐
- 和为s的两个数字VS和为s的连续证正数序列
- 了解点Dispatcher
- #343Div2-629C Famil Door and Brackets动态规划
- (水)大臣的旅费 蓝桥杯 树的直径
- 我的进度条
- 作业三
- JPA hibernate spring repository pgsql java 工程(二):sql文件导入数据,测试数据
- 基于FUSE框架的文件系统-课程设计
- IO编程
- 设备中断绑定到特定CPU(SMP IRQ AFFINITY)
- 2016年3月16
- 最小生成树 prim算法
- 字符串"true"转换为布尔型boolean「true」
- hadoop面试题总结1
- HD1160FatMouse's Speed(最长单调递增子序列)
- 在Delphi中使用C++对象(两种方法,但都要改造C++提供的DLL)
- 第五十四天
- 判断数字 字母 isDigit(), isalpha()
- 字符串工具类TextUtils
- Beautiful Soup 安装以及lxml的安装