Prime Ring Problem—hdu1016(DFS)
2016-05-06 14:27
344 查看
Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 40339 Accepted Submission(s): 17813
[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
___________________________________________________________________________________________________________________________
题目的意思是讲1到n的每个数构成一个环,相邻两个数之和为素数,将符合的结果按字典序全部输出;
方法采用的是DFS,将每个数都遍历一边,找出符合的情况;
#include<iostream> #include<cstring> #include<cstdio> #include<cmath> #include<string> #include<algorithm> #include<queue> using namespace std; int n; int a[25];//保存结果 int flag[25];//记录一个数是否已用过 bool isprime(int n) { if (n == 1 || n == 0) return 0; if (n == 2) return 1; for (int i = 2; i <= sqrt((double)n); i++) { if (n%i == 0) return 0; } return 1; } void dfs(int tot) { if (tot == n-1) { if (isprime(a[n - 1] + a[0])) { int o = 0; for (int i = 0; i < n; i++) { while (o++) { printf(" "); break; } printf("%d", a[i]); } printf("\n"); } return; } for (int i = 2; i <= n; i++) { if (flag[i] == 0) { if (isprime(a[tot] + i)) { flag[i] = 1; a[tot + 1] = i; dfs(tot + 1); flag[i] = 0; } } } } int main() { int k = 1; while (~scanf("%d", &n)) { printf("Case %d:\n", k++); a[0] = 1; memset(flag, 0, sizeof(flag)); dfs(0); printf("\n"); } return 0; }
相关文章推荐
- xpath语法
- Eclipse Android NDK环境搭建
- CentOS7 PostgreSQL 主从配置( 一)
- Android开发初学者必看文档:Android开发规范
- 算法的时间复杂度
- lr中IP wizard问题解决
- vi编辑器常用命令
- status bar 补充更改
- Programming with Objective-C(五)
- iOS开发-UITextField 使用全面解析
- Extjs控件属性总结
- javascript之function对象包括call()和apply()
- 如何选择适合自己的CMS建站系统
- Volley 源码解析
- Yarn源码分析之MapReduce作业中任务Task调度整体流程(一)
- ubuuntu使用笔记
- SQL语句大全
- 简单的textField 应用 逻辑很混乱。
- javaIO流 FileReader 的readLIne 和 read的区别
- TensorFlow学习笔记之一——初步印象