hdu1016 Prime Ring Problem(dfs)
来源:互联网 发布:js中json转数组 编辑:程序博客网 时间:2024/05/22 08:09
搜索的水很深啊,还是先从简单的题做起吧
题目很容易理解,给定大于0小于20的数字n;
求出由n个数字组成的环;
该环每相邻的两个数之和为素数
这n个数字有1,2....n-1,n组成,不能有重复!
每个环从都1开始
输出按照字典序从小到大输出所有可能;
原题要求:
Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 29191 Accepted Submission(s): 13001
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.
Note: the number of first circle should always be 1.
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.
You are to write a program that completes above process.
Print a blank line after each case.
Sample Input
68
Sample Output
Case 1:1 4 3 2 5 61 6 5 2 3 4Case 2:1 2 3 8 5 6 7 41 2 5 8 3 4 7 61 4 7 6 5 8 3 21 6 7 4 3 8 5 2
#include<iostream>#include <math.h>#include <string.h>using namespace std;int a[22], n, vist[22];int is_prime(int n){ int m = (int)sqrt(n); for (int i = 2; i <= m; i++) if (n % i == 0) return 0; return 1;}void difs(int cur){ if (cur == n && is_prime(a[0] + a[n - 1])) { for (int i = 0; i < n - 1; i++) cout << a[i] << " "; cout << a[n - 1] << endl; } else { for (int i = 2; i <= n; i++) if (!vist[i] && is_prime(i + a[cur - 1])) { a[cur] = i; vist[i] = 1; difs(cur + 1); vist[i] = 0; } }}int main(){ int i, j = 1; while (cin >> n) { memset(vist, 0, sizeof(vist)); for (i = 0; i < n; i++) a[i] = i + 1; cout << "Case " << j << ":" << endl; difs(1); cout << endl; j++; } return 0;}
0 0
- HDU1016-Prime Ring Problem(DFS)
- hdu1016(Prime Ring Problem)- dfs+枚举
- hdu1016 Prime Ring Problem(dfs)
- hdu1016 Prime Ring Problem(dfs)
- hdu1016 Prime Ring Problem(回溯dfs)
- hdu1016 Prime Ring Problem(dfs)
- HDU1016 Prime Ring Problem (DFS)
- HDU1016 Prime Ring Problem(dfs)
- HDU1016:Prime Ring Problem(dfs)
- HDU1016:Prime Ring Problem(DFS)
- hdu1016 Prime Ring Problem(DFS)
- Hdu1016 Prime Ring Problem(DFS)
- HDU1016:Prime Ring Problem(DFS)
- HDU1016:Prime Ring Problem(DFS)
- hdu1016(Prime Ring Problem)
- hdu1016 Prime Ring Problem()
- HDU1016——Prime Ring Problem(dfs,输入格式)
- HDU1016 Prime Ring Problem 解题报告--dfs
- 黑马程序员——OC中的封装
- 如何防止PendingIntent打开一个Activity的多个实例
- 计算机二级办假证
- poj 3370/2356 鸽巢原理
- URAL 2052 Physical Education(数位dp+二分)
- hdu1016 Prime Ring Problem(dfs)
- 算法设计与分析:第五章 回溯法 5.4素数环
- Rice- IIIP (2)
- 从JavaScript 数组去重看兼容性问题,及性能优化(摘自玉伯博客)
- 【阅读】《head first html5》第九章——在本地存储
- 算法设计与分析:第五章 回溯法 5.5马的遍历
- 心情日记
- 算法设计与分析:第五章 回溯法 5.6找n个数中r个数的组合
- Leetcode #242 Valid Anagram