【dfs】hdu 1016 素数环
来源:互联网 发布:余额宝优化投资可信吗 编辑:程序博客网 时间:2024/05/21 20:30
Prime Ring Problem
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.
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
图片就不放了。。做下笔记以后回来复习。。
code:
#include <iostream>#include <cmath>#include <cstring>using namespace std;int n,a[25],book[25];int prime(int x){ int i; for(i=2;i<=sqrt(x);i++) if(x%i==0) break; if(i<=sqrt(x)) return 0; else return 1;}void dfs(int step){ int first=1; a[n+1]=a[1]; a[1]=1; book[1]=1; if(step==n+1) { if(prime(a[n]+a[1])==0) return ;//判断最后一个数和第一个数的和是不是素数 for (int i=1;i<=n;i++){ if(first) first=0; else cout<<' '; cout<<a[i]; } cout<<endl; } //用递归实现dfs,满足条件输出,不满足条件直接返回 for(int i=2;i<=n;i++){ if(book[i]==0 && prime(i+a[step-1])){ //在循环的时候判断,避免超时,减少运算次数。。 a[step]=i; //第一个位置放的数为i book[i]=1; //表示已经用过i这个数 dfs(step+1);//递归调用 book[i]=0; //用完后还原,下次搜索时仍能访问 } } return ;}int main(){ int sum=1; memset(a,0,sizeof(a)); while(cin>>n){ cout<<"Case "<<sum<<':'<<endl; sum++; if(n%2==1) cout<<endl; //剪枝,不然会超时,数据太大 else { memset(book,0,sizeof(book)); dfs(2); cout<<endl; } } return 0;}
- hdu 1016 dfs(素数环)
- hdu 1016 dfs素数环
- 【dfs】hdu 1016 素数环
- nyoj 488&&hdu 1016 素数环【dfs】
- hdu 1016 素数环 经典dfs
- HDU 1016 素数环 简单的DFS
- hdu 1016 Prime Ring problem(dfs 素数环)
- HDU 1016 素数环 深度优先搜索(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)
- docker创建mysql容器
- vector 指针
- ORA-01653 表空间不足
- Java笔记7
- Linux 守护进程原理及实例(Redis、Nginx)
- 【dfs】hdu 1016 素数环
- copySign
- 设置允许外网访问MySQL数据库【Linux】
- CentOS 安装c/c++ 编译器
- 开心一下-换汽水问题
- 数据结构第二次作业
- Linux IO模型
- unity+Loom实现多线程(Thread)和主线程(MainThread)交互
- JAVA | 31