【日常练习】Prime Ring Problem(素数环)
2016-07-20 17:22
471 查看
Prime Ring Problem
Time Limit: 2000msMemory Limit: 32768KB 64-bit integer IO format: %I64d Java class name: MainA 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.
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.
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
大致题意判断给出的20以内的数,输出所有的小于这个数的序列。要求序列是当前位置和下一个位置相加的和是素数。首位相加也是素数
思路:
简单的深搜(dfs)题目,搜索过去就好了。
首先打表判断34以内的素数。接下来用一个布尔型的数组记录是否访问,然后用一个int型数组记录下来是素数环的序列。如果首尾相加是素数并且当前位置i和n相等表示搜索完毕,输出当前记录下来的素数环。
如果当前位置未访问并且当前位置和下一个位置相加为素数,记录j然后搜索下一个位置。
#include<bits/stdc++.h> using namespace std; bool isprime[38]; bool vis[18]; int record[18]; void isPrime(){ memset(isprime , true,sizeof(isprime)); isprime[0] = isprime[1] = false; for(int i = 2; i <= 34;i++){ if(isprime[i]){ for(int j = i+i;j <= 34;j+=i){ isprime[j] = false; } } } } void dfs(int i,int n){ if(i==n&&isprime[1 + record[n - 1]]){ for(int j = 0;j < n;j++){ if(j == n-1){ cout<<record[j]<<endl; } else{ cout<<record[j]<<" "; } } } else{ for(int j = 2;j <= n;j++){ if(!(vis[j]) && isprime[j + record[i-1]]){ record[i] = j; vis[j] = true; dfs(i + 1,n); vis[j] = false; } } } } int main(){ int mark = 1; int n; isPrime(); while(cin>>n){ printf("Case %d:\n",mark++); memset(vis,false,sizeof(vis)); record[0] = 1; vis[1] = true; dfs(1,n); cout<<endl; }return 0; }
相关文章推荐
- Win2003利用dfs(分布式文件系统)在负载均衡下的文件同步配置方案
- win2003分布式文件系统(dfs)配置方法[图文详解]
- win2003分布式文件系统及其部署 图文教程
- Hadoop2.6+jdk8的安装部署(1)——使用jar包安装部署【详细】
- Hadoop FS Shell
- DFS使用方法总结
- FastDFS注意事项
- 无忧技术带您预览DFS(分布式文件系统)管理控制台
- C 语言实现迷宫 DFS算法
- 一幅图弄清DFT与DTFT,DFS的关系
- HDFS---Namenode
- HDFS ---- Services startup
- POJ1523 SPF dfs
- poj1731 Orders dfs
- Surrounded Regions
- Binary Tree Zigzag Level Order Traversal,Restore IP Addresses,Word Search,Simplify Path
- DFS基础(1)
- HDU1241 Oil Deposits
- DFS算法有趣小题目
- HDU 1016 Prime Ring Problem