HDU 1016 dfs+回溯
来源:互联网 发布:app 是什么软件 编辑:程序博客网 时间:2024/05/16 04:32
Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 34810 Accepted Submission(s): 15416
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
素数环算是经典的问题了,主要是用回溯法。如满足条件就继续,如不满足就不继续。但是不能就简单return回去,因为在这一层用过数在上一层可以继续用,因此,开一个vis数组,记录数组i用过没有,开始用vis[i] = 1,表示用过,在第Z层里由于存在for循环,因此i++后是不可能再取到i的。在递归的下一层Z+1,由于已经设置了vis[i] = 1,因此下一层是不会填i的。而过后又vis[i] = 0;表示又可以在和Z上一层Z-1的另一阶X中递归用到。重复这个过程,整个递归树只执行有效的递归,一旦出现不符合要求的值时就返回。
#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>using namespace std;int prime[50];bool p[50];int vis[50];int a[40];int Ai(int n){ int i,j,k = 0; for(i = 2;i<=n*2;i++) p[i] = true; for(i = 2;i<=n*2;i++){ if(p[i]) prime[k++] = i; for(j = 2*i;j<=n*2;j+=i) p[j] = false; } return k;}void dfs(int n,int cur){ int i,j; bool ok,ok1; if(cur == n&&p[a[0]+a[n-1]]){ printf("%d",a[0]); for(i = 1;i<n;i++) printf(" %d",a[i]); printf("\n"); return ; } for(i = 2;i<=n;i++) if(!vis[i]&&p[i+a[cur-1]]){ a[cur] = i; vis[i] = 1; dfs(n,cur+1); vis[i] = 0; }}int main(){ Ai(40); int i,j; int n,cnt = 1; while(scanf("%d",&n)!=EOF){ memset(vis,0,sizeof(vis)); a[0] = 1; printf("Case %d:\n",cnt++); dfs(n,1); printf("\n"); } return 0;}
- HDU 1016 dfs+回溯
- hdu 1016 dfs+回溯
- hdu 1045 DFS+回溯
- HDU 1015 dfs回溯
- hdu 1045 DFS回溯
- HDU 1242 Rescue - DFS 回溯
- HDU 1015 爆搜 /dfs+回溯
- HDU 1181 DFS回溯思想
- HDU 1015 safecraker (DFS 回溯)
- hdu 2616 dfs回溯暴力
- hdu 5113(dfs+剪枝+回溯)
- 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 1016 Prime Ring Problem(经典DFS+回溯)
- HDU 1016 Prime Ring Problem (DFS回溯)
- 【DFS 回溯】HDU 1045 Fire Net
- CF574B Bear and Three Musketeers 简单的图,暴力
- android中所有颜色代码
- Leetcode231 Power of Two
- 求出1-100之间所有的素数(只能被1和它本身整除),要求每5个换行输出。
- http协议详解
- HDU 1016 dfs+回溯
- 文章标题
- iOS开发 顶部状态栏的隐藏
- scala实现设计模式之中介者模式
- extract the x509 ssl certificate from a pcap file
- [objective_[getter器和setter器的使用]
- NoSQL
- HDU1025 - Constructing Roads In JGShining's Kingdom (最长上升子序列)
- AWR format 工具的使用