相邻数字相加为质数
2015-07-30 20:16
281 查看
题意:
A ring is composed of n (even number) circles as shown in diagram. Put natural numbers
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.
You are to write a program that completes above process.
思路分析:
哈!DFS!
1、可以从第二个数开始放(题目要求第一个数为1),每次放一个数要跟前面的数相加,判断是否为质数。
是:标记该数已经用过,可以继续往下放
否:撤销标记,回溯上一个数
2、判断越界:数字都用完了&&最后一个数跟第一个数相加也是一个质数
源代码:
心得:
瞬间发现DFS的题就是按照模板在做题。。。。嗯,细节还是要注意的!
A ring is composed of n (even number) circles as shown in diagram. Put natural numbers
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 <= 16)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.You are to write a program that completes above process.
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
思路分析:
哈!DFS!
1、可以从第二个数开始放(题目要求第一个数为1),每次放一个数要跟前面的数相加,判断是否为质数。
是:标记该数已经用过,可以继续往下放
否:撤销标记,回溯上一个数
2、判断越界:数字都用完了&&最后一个数跟第一个数相加也是一个质数
源代码:
#include<iostream> #include<cstring> using namespace std; int n; int pri[11] = { 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 }; //质数表 int ans[20]; //储存给的数 int used[20]; //用来标记用过的数 int is_pri(int a, int b) //判断相加是否是质数 { int w = 0; for (int i = 0; i < 10; i++) { if (a + b == pri[i]) return 1; } return 0; } void dfs(int a) { if (a == n && is_pri(ans[0], ans[n - 1])) //结束条件 { for (int i = 0; i < n; i++) { if (i == n - 1) { cout << ans[i]; //最后一个单独输出,要求格式。 break; } cout << ans[i] << " "; }cout << endl; } else for (int i = 2; i <= n; i++) if (!used[i] && is_pri(i, ans[a - 1])) { used[i] = 1; //该数已经使用 ans[a] = i; //把i放进a位置 dfs(a + 1); used[i] = 0; //清除使用记录(不满足的数) } } int main() { memset(ans, 0, sizeof(ans)); memset(used, 0, sizeof(used)); ans[0] = 1; //题目要求,第一个数要为1. int count = 0,k=0; while (cin >> n) { if (k++) cout << endl; count++; if (n == 0) return 0; printf("Case %d:\n", count); dfs(1); } return 0; }
心得:
瞬间发现DFS的题就是按照模板在做题。。。。嗯,细节还是要注意的!
相关文章推荐
- ASP.NET MV 4000 C - html.beginForm在javascript中获取form信息
- web.xml中上下文参数
- 敌兵布阵
- [BZOJ3685]普通van Emde Boas树
- Spark SQL and DataFrame Guide(1.4.1)——之Data Sources
- 【linux高级程序设计】(第十二章)Linux多线程编程 3
- 单调栈练习题题解
- 链接错误'undefined reference to'与gcc参数 -l -L -I
- 课堂随记
- dotNet使用HttpWebRequest模拟浏览器
- Quality control
- ssh publickey
- HDU 5327 区间里由不同的数字组成的数的个数-set-(枚举)
- BAPI_ACC_DOCUMENT_POST
- Java错误提示-------java.sql.SQLException:ResultSet is closed
- 解决ORA-29857:表空间中存在域索引和/或次级对象 & ORA-01940:无法删除当前连接的用户问题
- str_replace批量替换
- poj1442 Black Box【优先队列,定义两个队列】
- Android中注册和发送广播中添加权限
- 解决ORA-29857:表空间中存在域索引和/或次级对象 & ORA-01940:无法删除当前连接的用户问题 分类: oracle sde 2015-07-30 20:13 8人阅读 评论(0) 收藏