Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 25909 Accepted Submission(s): 11536
Total Submission(s): 25909 Accepted Submission(s): 11536
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.
![](https://i-blog.csdnimg.cn/blog_migrate/427b1dd2282412709d583cc17eda983e.gif)
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
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
Source
题意:给个数n,所谓的素数环,就是用1~n 的数连成一个环,且保证相邻的两数之和为素数,要求按逆时针输出各个符合要求的素数环。并且每次的第一个数都为1.
分析:坑爹的题啊,告诉小伙伴们一个血的教训,在输出每个素数环的时候,相邻两数之间有空格,但是最后一个数 后一定不能有空格,否则会判WA ,而不是PE(这就是最坑的地方!!!)
好了,言归正传。这题用的是回溯法,其实质的内容还是DFS,因为回溯法正是按照深度优先的顺序在遍历解答数,强大的DFS~~~。其实还有一种方法叫生成-测试法,但是遗憾的是,本题的 0<n<20 ,数据过大,生成-测试法只能打出n<16的排列,而且n越大,速度越慢。
PS:生成-测试法:就是初始化一个排列1,2,...,n,然后用C++库函数next_permutation(A+1,A+n)生成比第一个排列字典序大的下一个排列,一直循环下去,直到函数next_permutation(A+1,A+n)的返回值为0,此时就生成了1~n的所有全排列,只需在生成每个排列是判断是否符合要求,符合就输出即可)
AC代码:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <cmath>
#include <cstdlib>
#include <ctime>
#define INF 0x7fffffff
using namespace std;
const int maxn = 22;
int isp[42];
int n,A[maxn],vis[maxn];
int T = 0;
bool is_prime(int x) //判断是否是素数
{
int flag = 1;
for(int i=2;i*i<=x;i++) //这里的i*i<=x而不是i*i<x
if(x%i == 0) { flag = 0; break; }
return flag;
}
void dfs(int cur)
{
if(cur == n && isp[A[0]+A[n-1]]) //递归边界的判定
{
for(int i = 0;i < n-1; i++) printf("%d ",A[i]); //打印方案
printf("%d\n",A[n-1]); //注意:最后一个数的后面不能有空格
}
else
{
for(int i = 2;i <= n; i++) //尝试放置每个数i
{
if(!vis[i] && isp[i+A[cur-1]])//如果i没用过,且与前一个数之和为素数
{
A[cur] = i;
vis[i] = 1; //设置使用标志
dfs(cur+1);
vis[i] = 0; //清除使用标志
}
}
}
}
int main()
{
for(int i = 2;i <= 40; i++) isp[i] = is_prime(i); //生成素数表,加快后续判断
isp[0] = isp[1] = 1; //该句不加也能AC
while(scanf("%d",&n)!=EOF)
{
for(int i = 0;i < n; i++) vis[i] = 0;
T++;
A[0] = 1;
printf("Case %d:\n",T);
vis[1] = 1; //设置使用标志
dfs(1);
vis[1] = 0; //清除使用标志
printf("\n");
}
return 0;
}
//PS:一般的,如果在回溯中修改了辅助的全局变量,一定要及时恢复被修改的值