Prime Ring 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

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值