Prime Ring Problem
来源:互联网 发布:icloud中的备份恢复mac 编辑:程序博客网 时间:2024/05/24 05:45
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
思路:典型的深搜题,思想看代码
#include<stdio.h>#include<string.h>using namespace std;int a[20],vis[20],n;int prime(int m){ int i; for(i=2;i*i<=m;i++) if(m%i==0) return 0; return 1;}//判断素数函数int dsf(int step){ int i; if(step==n+1&&prime(a[n]+a[1]))//递归结束的条件,不要忘记判断最后一个数和第一个数的和是否是素数 { for(i=1;i<n;i++) printf("%d ",a[i]); printf("%d\n",a[n]); return 0; } for(i=2;i<=n;i++)//题目要求从一开始,所以这里从二开始循环 { if(!vis[i]&&prime(i+a[step-1]))//判断当前的数是否被用过,并且与上一个数的和是素数 { a[step]=i; vis[i]=1;//每用一次就标记上 dsf(step+1);调用递归函数 vis[i]=0;回溯的时候清零,以便下次用 } }}int main(){ int k=1; a[1]=1; while(scanf("%d",&n)!=EOF) { memset(vis,0,sizeof(vis));标记数组清零 printf("Case %d:\n",k++); dsf(2);从二开始 printf("\n"); } return 0;}
虽然题很水,但还是做了很长时间,这就是菜鸟的世界,你不懂。。。。。。
0 0
- 1016 Prime Ring Problem
- HDOJ1016-Prime Ring Problem
- HDU1016 Prime Ring Problem
- DFS__1195: Prime Ring Problem
- Prime Ring Problem
- 1016:Prime Ring Problem
- 1016 Prime Ring Problem
- HDUOJ1016 Prime Ring Problem
- 1016 Prime Ring Problem
- Prime Ring Problem
- hdu1016 Prime Ring Problem
- Prime Ring Problem(dfs)
- Prime Ring Problem
- Prime Ring Problem
- Prime ring problem
- hdu1016-Prime Ring Problem
- HDU1035 Prime Ring Problem
- 1016Prime Ring Problem
- JSP乱码过滤器
- UML九种图之状态图
- php-fpm的简单启动脚本
- android,意图,打开百度网址
- Eclipse如何点出方法
- Prime Ring Problem
- CIFS
- XML第一讲:XML基本讲解
- [Oracle SQL] 使用rollup分组统计按统计结果分组排序显示的问题
- iOS学习之2-使用ASIHttpRequest调用WebService
- hdu 1231 最长子序类
- UVALive 5135 Mining Your Own Business(BCC、割顶)
- 大数据量数据库优化
- JAVA中this用法小结