HDU 1016 Prime Ring Problem【深搜练习】
来源:互联网 发布:java导出csv文件乱码 编辑:程序博客网 时间:2024/05/29 18:32
Prime Ring Problem
Total Submission(s): 55230 Accepted Submission(s): 24442
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 4Case 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,对其进行排序,要求是当前数和其后一个数之和必须是素数,并且1永远都在第一位并和最后一个数之和也为素数。
解题分析:
其实就是用深搜对1~n的数列进行全排列,输出其中特定的序列。
AC代码:
#include<stdio.h>#include<string.h>#include<math.h>#define N 23int book[N], a[N] = {1}, n;int IsPrime(int m)//因为数据较小,也可以用一个数组来记录是否是素数{ if(m == 1) return 0; int i, k = (int)sqrt(m); for(i = 2; i <= k; i++) if(m%i == 0) return 0; return 1;}void dfs(int step){ int i; if(step >= n){ if(IsPrime(1+a[step-1])){ printf("1"); for(int j = 1; j < n; j++) printf(" %d", a[j]); printf("\n"); } return ; } for(i = 2; i <= n; i++){ if(!book[i] && IsPrime(a[step-1]+i)){ book[i] = 1; a[step] = i; dfs(step+1); book[i] = 0; } }}int main(){ int i, t = 0; while(~scanf("%d", &n)){ memset(book, 0, sizeof(book)); printf("Case %d:\n", ++t); dfs(1); printf("\n"); } return 0;}
- HDU 1016 Prime Ring Problem【深搜练习】
- hdu 1016 Prime Ring Problem dfs深搜算法
- hdu 1016 Prime Ring Problem
- hdu 1016 Prime Ring Problem
- hdu 1016 Prime Ring Problem
- HDU 1016 Prime Ring Problem
- hdu 1016 Prime Ring Problem
- HDU-1016 prime ring problem
- hdu 1016Prime Ring Problem
- hdu 1016 Prime Ring Problem
- HDU-1016 Prime Ring Problem
- HDU-1016-Prime Ring Problem
- hdu 1016 Prime Ring Problem
- hdu 1016 Prime Ring Problem
- hdu 1016 Prime Ring Problem
- hdu 1016 Prime Ring Problem
- Hdu 1016 Prime Ring Problem
- hdu 1016 Prime Ring Problem
- java中加号为连接字符与运算符的区别
- 使用Sqoop从MySQL导入数据到Hive和HBase 及近期感悟
- 模板实现顺序表、双链表
- 【Java】常用控件和事件处理
- JAVA笔记
- HDU 1016 Prime Ring Problem【深搜练习】
- 希尔排序与堆排序
- Java任务调度框架Quartz教程实例
- 模板的分离编译
- hibernate框架双向一对多例子(十一)
- Centos中安装配置local/standalone模式和伪分布式模式hadoop集群
- 动态规划之数字三角形
- 图像处理(七):图像变换
- SpringMVC使用iReport生成pdf