您的位置:首页 > 其它

【日常练习】Prime Ring Problem(素数环)

2016-07-20 17:22 471 查看

Prime Ring Problem

Time Limit: 2000msMemory Limit: 32768KB 64-bit integer IO format: %I64d Java class name: Main

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

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

大致题意判断给出的20以内的数,输出所有的小于这个数的序列。要求序列是当前位置和下一个位置相加的和是素数。首位相加也是素数

思路:

简单的深搜(dfs)题目,搜索过去就好了。

首先打表判断34以内的素数。接下来用一个布尔型的数组记录是否访问,然后用一个int型数组记录下来是素数环的序列。如果首尾相加是素数并且当前位置i和n相等表示搜索完毕,输出当前记录下来的素数环。

如果当前位置未访问并且当前位置和下一个位置相加为素数,记录j然后搜索下一个位置。

#include<bits/stdc++.h>
using namespace std;

bool isprime[38];
bool vis[18];
int record[18];

void isPrime(){
memset(isprime , true,sizeof(isprime));
isprime[0] = isprime[1] = false;
for(int i = 2; i <= 34;i++){
if(isprime[i]){
for(int j = i+i;j <= 34;j+=i){
isprime[j] = false;
}
}
}
}
void dfs(int i,int n){
if(i==n&&isprime[1 + record[n - 1]]){
for(int j = 0;j < n;j++){
if(j == n-1){
cout<<record[j]<<endl;
}
else{
cout<<record[j]<<" ";
}
}
}
else{
for(int j = 2;j <= n;j++){
if(!(vis[j]) && isprime[j + record[i-1]]){
record[i] = j;
vis[j] = true;
dfs(i + 1,n);
vis[j] = false;
}
}
}
}
int main(){
int mark = 1;
int n;
isPrime();
while(cin>>n){
printf("Case %d:\n",mark++);
memset(vis,false,sizeof(vis));
record[0] = 1;
vis[1] = true;
dfs(1,n);
cout<<endl;
}return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  DFS