Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 36533 Accepted Submission(s): 16102
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
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 2 3 4 5 6..... n 中锁有数字组成的素数环并输出出。 素数环的定义: 环中任意相邻的两个数的和是一个素数; 思路: 直接dfs 搜一遍就可以了, n最大是20 不会超时 我的代码:
#include
using namespace std;
const int maxn = 22;
int vis[maxn];
int n;
int ans[maxn];
int cheak(int k) //函数功能是 检查k是不是素数
{
int falt = 1;
for(int i = 2; i < k; i++)
if(k % i == 0)
falt = 0;
return falt;
}
int dfs(int t)
{
if(t == n +1 && cheak(ans[1] + ans[n])) //如果检查成功了就输出环
{
for(int i = 1 ; i <= n; i++)
i == n ? printf("%d\n", ans[i]) : printf("%d ", ans[i]);
}
for(int i = 2; i <= n; i++) //位置i的所有可能
{
if(cheak(i + ans[t - 1])&& !vis[i]) //检查
{
vis[i] = 1; //DFS 这里注意设为1, 为了避免重复及死递归
ans[t] = i;
dfs(t+1);
vis[i] = 0; //DFS 这里注意归0, 为了避免重复及死递归
}
}
}
int main()
{
int Case = 1;
while(scanf("%d", &n) == 1 && n)
{
memset(vis, 0, sizeof(vis)); //将访问数组归0;
ans[1] = 1; // 1 被固定, 故在开始就设为1
vis[1] = 1; //1 被固定, 故在开始就设为1
printf("Case %d:\n", Case++);
dfs(2); // 从2 开始扫, 因为1被固定了
printf("\n");
}
}