Prime Ring Problem 素数环问题
来源:互联网 发布:美国恐怖故事 知乎 编辑:程序博客网 时间:2024/06/10 08:25
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.
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.
You are to write a program that completes above process.
Print a blank line after each case.
Sample Input
68
Sample Output
Case 1:1 4 3 2 5 61 6 5 2 3 4Case 2:1 2 3 8 5 6 7 41 2 5 8 3 4 7 61 4 7 6 5 8 3 21 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"); }}
0 0
- Prime Ring Problem 素数环问题
- Prime Ring Problem(素数环问题)
- 题目1459:Prime ring problem(素数环问题)
- HDU 1016 Prime Ring Problem(DFS 素数环问题)
- HD 1016 Prime Ring Problem(素数环问题)
- HDU 1016 Prime Ring Problem 素数环
- HDU_1016 Prime Ring Problem 素数环
- hdu1016-Prime Ring Problem 素数环
- hdu1016 Prime Ring Problem 素数环
- hdoj 1016 Prime Ring Problem【素数环】
- hdu 1016 Prime Ring Problem (素数环)
- 1016-Prime Ring Problem,素数环,深搜!
- hdu 1016 Prime Ring Problem 素数环
- DFS:Prime Ring Problem(素数环)
- Prime Ring Problem(素数环 深搜)
- 素数环(Prime Ring Problem, Uva 524)
- UVA-524 Prime Ring Problem 素数环
- hdoj problem 1016 Prime Ring Problem(素数环&&素数问题+DFS(回溯法))
- c++的异常
- Error: Ram free start is after ram end. Fatal error hit, exiting...
- FTGL库初步剖析
- 和飞电风扇
- ACPI<Advanced Configuration and Power Interface >
- Prime Ring Problem 素数环问题
- 蓝桥杯——买不到的数目
- 用户界面View之ViewGroup
- HIve join详解
- 在mac上安装和使用mysql-5.6.24
- 数据库事务隔离级别
- android 开发环境的效率匹配(host修改和http抓包)
- 短信监听
- 转义字符