Prime Ring Problem(DFS)

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)让你把这些数字放入一个环中,要求相邻的两个数字相加是质数,例如Case 1 中的1 4 3 2 5 6相邻的数字相加都是质数,特别的是开头要与结尾相加是质数,因为围成的是一个环。

思路:递归DFS 除了第一个数字'1'固定了,其他数字都要一一去试探,从第二个数字开始,依次判断这个数与前一个数相加是不是质数并且这个数没有被使用,若满足则将它存入答案数组中,否则继续往下扫。当答案数字满了的时候,即要存入的数字个数等于输入的n 时要将这一组解输出。然后继续寻找下一组解。


AC代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#include<queue>
#include<set>
#include<map>
#include<vector>
#include<stack>
using namespace std;
#define ll long long
int n,step;
int a[25],mark[25];   //数组a作用是存合法的一组解,数组mark表示某位置的数字是否被使用
bool check(int num){            //检查是不是质数
    for(int i=2;i*i<=num;i++)
        if(num%i==0)return true;
    return false;
}
void dfs(int x){
    step++;          //位置加一
    a[step]=x;       //第几位就存第几个数
    if(step==n){     //若到了最后一位了,则与第一个数即“1”再做质数判断
        if(!check(a[step]+1)){    //若相加是质数则依次输出
            for(int i=1;i<=step;i++){
                if(i!=step)
                    printf("%d ",a[i]);
                else
                    printf("%d",a[i]);
            }
            printf("\n");
        }
        return;
    }
    for(int i=2;i<=n;i++){ //从2开始(1已经固定了)试,依次加一
        if(!check(x+i)&&!mark[i]){  //若这个数加前面一个数是质数并且这个数并未被使用则将这个数加入到的数组a中(开始的a[step]=x)
            mark[i]=1;     //将使用了的数字对应位置标记为1,防止重复使用
            dfs(i);       //向下试下一个数,进入下一重循环
            mark[i]=0;   //若后面试出了一组答案试将第i位置也就是数i释放,这是回溯过程
            step--;       //相应的位置减一
        }
    }
}
int main()
{
    int cases=1;
    while(scanf("%d",&n)!=EOF){
        memset(a,0,sizeof(a));
        memset(mark,0,sizeof(mark));
        step=0;             //定义填入数字的位置
        printf("Case %d:\n",cases++);
        dfs(1);         
        printf("\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值