您的位置:首页 > 其它

Prime Ring Problem

2016-07-24 08:58 197 查看
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

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

本题的大致意思是要在一个环里面放1-n个数,且相邻的数加起来要是质数,环里面的数要从1开始。

解题思路是从第二个空开始枚举每一个数,如果和第一个数相加为质数,就再对下一个空进行枚举,如果没有满足条件的数就返回上一个空枚举下一个没有使用过的数,一直枚举到最后一个空,输出。

注意对于最后一个空要判断和1相加是否为质数。

解题代码如下:

#include <iostream>
#include <string.h>
#define MAXN 20 + 5
using namespace std;
int a[MAXN];
int is_place[MAXN];
int n;
//判断是否是质数,本题数据不大,可以使用这个方法
bool is_prime(int num)
{
bool is_prime = true;
for(int i = 2; i * i <= num; i++)
{
if(num % i == 0)
{
is_prime = false;
break;
}
}
return is_prime;
}
//判断和前一个数相加是否为质数
bool can_place(int i)
{
bool place = true;
if(i == 1)
return true;
if(!is_prime(a[i] + a[i - 1]))
place = false;
if(i == n && !is_prime(a[i] + a[1]))
place = false;
return place;
}
//深度搜索
void dfs(int i, int n)
{
//如果最后一个空填完,输出
if(i > n)
{
for(int j = 1; j <= n; j++)
{
cout << a[j];
if(j != n)
cout << " ";
}
cout << endl;
}
else
{
a[1] = 1;
is_place[1] = 1;
//从第二个空开始枚举
for(int j = 2; j <= n; j++)
{
if(is_place[j] == 0)
{
a[i] = j;
if(can_place(i))
{
is_place[j] = j;
dfs(i+1,n);
is_place[j] = 0;
}
}
}
}
}

int main()
{
int i = 1;
while(cin >> n)
{
cout << "Case " << i << ":" << endl;
memset(is_place, 0, sizeof(is_place));
dfs(2,n);
cout << endl;
i++;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dfs 深度搜索 ACM