HDU 1016
来源:互联网 发布:全乒乓淘宝 编辑:程序博客网 时间:2024/05/23 20:21
Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 29284 Accepted Submission(s): 13047
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.
Inputn (0 < n < 20).
OutputThe 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 Input68
Sample OutputCase 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
SourceAsia 1996, Shanghai (Mainland China)
Note: the number of first circle should always be 1.
You are to write a program that completes above process.
Print a blank line after each case.
68
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
给你一个数N。让你求在一到N之间的整数,是否相邻两个能组成素数,如能能则输出组合方式。
一道经典的DFS搜索问题,这种问题很难用文字表达清楚,我尽量吧。
代码:
#include <stdio.h>#include <string.h>int vis[50]; //用来标记一个数是否被用过。int a[50]; // 用来存放可行的数。int cc;int n;int cccc=0;bool is_sushu(int b){ int i; for(i=2;i*i<=b;i++) { if(b%i==0) return false; } return true; //素数判断。}void dfs(int num) //num是填入的第一个数。{ if(num==n &&is_sushu(a[0]+a[n-1])) //如果num==n则输出, { for(cc=0;cc<n;cc++) { if(cc!=n-1) printf("%d ",a[cc]); else printf("%d\n",a[cc]); } } else { int i; //这个int i要定义在这里,很重要。 for(i=2;i<=n;i++) //从2开始,因为题目说过,第一个数一定是1. { if(vis[i]==0 &&is_sushu(a[num-1]+i)) //如果这个数没被用过,并且上一个数加这个数为素数 { a[num]=i;//将这个数存入数组。 vis[i]=1; //令它为一。表示用过。 dfs(num+1); //继续填数。 vis[i]=0; //回溯。 } } }}int main(){ while(~scanf("%d",&n)) { printf("Case %d:\n",++cccc); memset(vis,0,sizeof(vis)); a[0]=1; //第一个数为一。 dfs(1); // 填数。 printf("\n"); }}
0 0
- HDU 1016
- HDU 1016
- HDU 1016
- hdu-1016
- 1016 hdu
- hdu 1016
- hdu 1016
- hdu 1016
- HDU 1016
- HDU 1016
- hdu 1016
- HDU 1016
- hdu 1016
- hdu 1016
- hdu 1016
- hdu-1016
- hdu 1016
- HDU 1016
- iOS新浪微博客户端开发(1)——新特性界面
- Andriod Input子系统框架
- 搭建mysql的master-slave环境(mysql主从复制)
- VS2012发布网站详细步骤问题
- 04-1. 水仙花数(20)
- HDU 1016
- Hive常见错误
- 在 Mac OS X 终端里使用 Solarized 配色方案
- TCP并发复制上传文件
- 实习篇---第四十四天
- 一道程序员面试的经典悖论问题
- OS开发之键盘类型UIKeyboardType (图片效果)
- Redis研究(十七)—SORT排序
- 工作日记-张吉林