dfs hdu 1016 Prime Ring Problem 素数环
来源:互联网 发布:快消品行业数据 编辑:程序博客网 时间:2024/05/16 07:37
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.
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
题意:
给一个n求n的全排列中相邻两个和是素数包括第一个和最后一个的排列;
思路:
由于n最大20所以可以打一个素数表, if(num==n&&prime[a[n-1]+a[0]])搜索结束条件,其他的看注释;
代码:
#include<cstdio>#include<iostream>#include<algorithm>#include<cstring>#include<cmath>using namespace std;int prime[40]= {0,0,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1};int n;int a[100],vis[100];void dfs(int num){ if(num==n&&prime[a[n-1]+a[0]]) { for(int i=0; i<n-1; i++) { printf("%d ",a[i]); } printf("%d\n",a[n-1]); } else { for(int i=2; i<=n; i++) { if(!vis[i]&&prime[i+a[num-1]]) { vis[i]=1;//标记; a[num]=i;//num此时等于1//由于第一个数是1,所以1已经被用过了,得从2开始往数组a里面存; dfs(num+1); vis[i]=0; //回溯; } } }}int main(){ int t=0; while(~scanf("%d",&n)) { t++; printf("Case %d:\n",t); memset(vis,0,sizeof(vis)); a[0]=1; dfs(1); printf("\n"); }}
- hdu 1016 Prime Ring problem(dfs 素数环)
- Hdu 1016 Prime Ring Problem (素数环经典dfs)
- hdu-1016 Prime Ring Problem(素数环 dfs)
- HDU 1016 Prime Ring Problem(DFS 素数环问题)
- hdu-1016Prime Ring Problem(素数环 dfs)
- hdu-1016 Prime Ring Problem(素数环) DFS解法
- hdu 1016 Prime Ring Problem(dfs,素数环)
- HDU (dfs)1016 Prime Ring Problem素数环
- hdu 1016Prime Ring Problem dfs经典题 素数环
- dfs hdu 1016 Prime Ring Problem 素数环
- HDU 1016 Prime Ring Problem (素数环)(DFS)
- HDU 1016 Prime Ring Problem 素数环
- hdu 1016 Prime Ring Problem (素数环)
- hdu 1016 Prime Ring Problem 素数环
- HDU 1016 Prime Ring Problem(DFS回溯+素数判断)
- 【HDU 1016】Prime Ring Problem(DFS、素数筛)
- DFS:Prime Ring Problem(素数环)
- HDOJ-1016-Prime Ring Problem(素数环)【DFS】
- numpy常用操作
- webpack v1.x使用
- 遍历 Map 的四种方法
- IA32汇编语言——理解函数调用时栈内容的变化
- 查看自己生日是否在pi中
- dfs hdu 1016 Prime Ring Problem 素数环
- 利用JAVA求定积分
- op分析
- pcl1.8.0+vs2015配置安装【小白入门与遇到过的问题解决】
- 常用命令
- 冒泡,选择,插入排序
- python绘图---matplotlib几个简单例子
- 2017年最新JRebel+Eclipse热部署教程
- 盘点8种CSS实现垂直居中水平居中的绝对定位居中技术