Prime Ring Problem 素数环问题
2015-05-25 22:52
330 查看
Prime Ring Problem
Problem DescriptionA 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
题意不难理解,即一个环,由1~n组成,任意相邻的两个数之和为素数
主要是代码方面,原以为写了很多dfs这方面的代码,但是这次写仍然遇到了问题:
1.dfs里自己写的很乱
2.不够优化,比如判断素数时,想到了素数打表,但没想到用0,1代表是否为素数,下标代表这个数。
3.还可以更优化—n为奇数的时候不可能形成素数环,此处优化下面代码中未体现
附代码如下
#include<stdio.h> #include<string.h> int is_prime[]= {0,1,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,0,0},n; int visited[21],a[21]; int flog; void dfs(int step) { if(step==n&&is_prime[a[n-1]+1]) { flog=0; for(int i=0; i<n-1; i++) printf("%d ",a[i]); printf("%d\n",a[n-1]); return; } for(int i=2; i<=n; i++) { if(visited[i]==0) { if(is_prime[a[step-1]+i]) { visited[i]=1; a[step++]=i; dfs(step); visited[i]=0; step--;//写的时候把这条语句没写,汗··· } } } } int main() { int j=1; while(~scanf("%d",&n)) { flog=1; printf("Case %d:\n",j++); memset(visited,0,sizeof(visited)); a[0]=1; dfs(1); if(flog==1) printf("No Answer\n"); } }
相关文章推荐
- HD 1016 Prime Ring Problem(素数环问题)
- Prime Ring Problem(素数环问题)
- 题目1459:Prime ring problem(素数环问题)
- HDU 1016 Prime Ring Problem(DFS 素数环问题)
- hdu 1016 Prime Ring Problem 素数环
- HDOJ-1016 Prime Ring Problem 素数环 DFS
- hdoj 1016 Prime Ring Problem【素数环】
- hdu1016-Prime Ring Problem 素数环
- 递归--【全排列问题】九度1459.Prime ring problem
- Prime Ring Problem (素数环)深度优先搜索
- 递归与回溯 HDOJ 2553 N皇后问题 1016 Prime Ring Problem
- HDOJ-1016-Prime Ring Problem(素数环)【DFS】
- hdu-1016 Prime Ring Problem(素数环) DFS解法
- UVA - 524 Prime Ring Problem (经典回溯问题)
- hdoj problem 1016 Prime Ring Problem(素数环&&素数问题+DFS(回溯法))
- HDU-1016 Prime Ring Problem【素数环 打表+深搜】
- HDU 1016 Prime Ring Problem(素数环)
- 杭电OJ(HDOJ)1016题:Prime Ring Problem(DFS问题)
- hdu 1016 Prime Ring Problem(素数环)
- ZOJ-1457 prime ring problem 素数环 题解