Prime Ring Problem
Time Limit:2000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
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.
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
题目大意:
给出一个数 n ,用 1 - n 组成一个环,这个换的要求是,从 1 开始,并且每两个相邻的数的和都为素数
分析:
这就是典型的素数环,刘汝佳《算法竞赛入门经典》 上有讲解,我在这就不多说了,
每次选一个数,判断这个数和前一个数的和是否为 素数,如果是进行下一个数,否则换数,如果这个数 是第 n 个数,那么需要判断是否与第一个数的和也为素数。这里面判断素数的时候不能够每次都用判断素数的方法判断一遍,那样会超时,用一个数组直接事先打一个素数表就行了
附上代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
#include <algorithm>
#include <map>
using namespace std;
/*
* 筛选法素数打表
*/
const int MAXN = 100;
bool is_prime[MAXN];
void init()
{
memset(is_prime,true,sizeof(is_prime));
is_prime[0] = is_prime[1] = false;
for(int i = 2;i < MAXN;i++)
{
if(is_prime[i])
{
for(int j = i * i;j < MAXN;j+=i)
{
is_prime[j] = false;
}
}
}
}
int visit[100];
int n;
void DFS(int t,int ans[])
{
if(t > n)
return;
if(t == n && is_prime[ans[n - 1] + ans[0]])
{
for(int i = 0;i < n;i++)
{
if(i != 0)
printf(" ");
printf("%d",ans[i]);
}
printf("\n");
}
for(int i = 1;i <= n;i++)
{
if(!visit[i] && is_prime[ans[t - 1] + i])
{
ans[t] = i;
visit[i] = 1;
DFS(t + 1,ans);
visit[i] = 0;
ans[t] = 0;
}
}
}
int main()
{
init();
int flag = 1;
while(cin >> n)
{
printf("Case %d:\n",flag++);
memset(visit,0,sizeof(visit));
int ans[100] = {0};
ans[0] = 1;
visit[1] = 1;
DFS(1,ans);
printf("\n");
}
return 0;
}