HDU 1016 Prime Ring Problem

来源:互联网 发布:实时数据库应用 编辑:程序博客网 时间:2024/05/16 10:31

Prime Ring Problem

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 39008    Accepted Submission(s): 17213


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
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
 

题目大意:给定一个正整数n(0<n<20),然后将1-n排在一个圆环上面,要求每相邻的两个整数相加起来是素数。
思路:DFS+剪枝。用深搜求出所有的排列然后判断每一个排列是否满足题目要求。
           如果不剪枝的话肯定要超时,事实证明也确实是这样,第一次不信邪没有简直提交果断超时,然后简单的剪了一下,AC了。
           题目还是比较简单的,很容易理解,比之前做的HDU1010需要奇偶剪枝的容易了不知道多少倍~
           然后还有一个要注意的地方是输出,每输出一个测试数据就换一下行,不是每两组测试数据之间换行,之前也因为这个表达错误了一次。


AC代码:

#include<iostream>#include<cstring>using namespace std;int cir[25], isFind[25];//isFind数组用来记录数是否已经被用过bool isPrime(int n)//判断素数{int i = 2;for (; i < n; i++){if (n % i == 0) return 0;}return 1;}void dfs(int i, int n){if (i >= n){if (isPrime(cir[n-1] + cir[0]))// 最后判断最后一个数字和第一个数字的和是不是素数for (int x = 0; x < n; x++)if(x != n -1) cout << cir[x] << " ";else cout << cir[x] << endl;}int j;for (j = 2; j <= n; j++){if (isFind[j]) continue;cir[i] = j;isFind[j] = 1;if ( !isPrime(cir[i - 1] + cir[i]) ) //判断当前数与之前一个数的和是不是素数, 不是就直接pass, 也就是剪枝{isFind[j] = 0;//如果不满足,就恢复数字的使用标记,进行下一次循环continue;}dfs(i + 1, n);isFind[j] = 0;// 恢复数字的使用标记}}int main(){int n, i, count = 0;while (cin >> n){cout << "Case " << ++count << ":" << endl;memset(cir, 0, sizeof(cir));memset(isFind, 0, sizeof(isFind));cir[0] = 1;//题目规定第一个数字必须是1dfs(1, n);//从i=1即第二个数字开始向下搜索cout << endl;}return 0;}

0 0