杭电OJ——1016 Prime Ring Problem
题目链接http://acm.hdu.edu.cn/showproblem.php?pid=1016
Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 90468 Accepted Submission(s):
37079
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 题解:题目意思就是让你实现一个包含n个圆的圆环,这个圆环中的圆填1-n的数,且1-n的每个数都要填上去。第一个圆必须填1,然后填数,使圆环中任意一个相邻的数的和都为素数。输出所有满足的情况 这题看到数据范围只到20,简单粗暴的想法就是先错排所有可能的情况,然后输出符合条件的情况,这样想的就自己去去实现一下了,在这里我就不再多说了、、、、、 此题我们用到的是dfs深度优先搜索,每次搜索就是一个一个圆dfs,每次到达一个圆,我们要在这个圆中填上还没有填过的并且与前一个数相加仍然是素数的数,直到判断到最后一个圆的时候,多加 判断这个数是否与第一个圆中的1相加为素数,如果满足,则输出这种排列 判断每次是否是素数,可以提前打表,以节省程序运行的时间 ac的代码:
//素数环的问题 #include#include #include using namespace std; int prime[40]={ 0 ,1 , 2, 3, 0, 5, 0, 7, 0, 0, 0 ,11, 0,13, 0, 0, 0,17, 0,19, 0 ,0 , 0,23, 0, 0, 0, 0, 0,29, 0 ,31, 0, 0, 0, 0, 0,37, 0, 0};//打表1到39素数 int n; int ans[20]={1,1};//记录是否已经用过,0,1相当于已经用了,所以初始化为1 int vec[22]={1}; void print(){ for(int i=0;i >n){ printf("Case %d:\n",flag++); dfs(1); cout<