Prime Ring Problem

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

//深搜有一种不撞南墙不回头的感觉,一直往下走,
//这里他怎么在回去呢,就是没有路了之后,
//他就会返回到上一个节点,看看他是不是还有别的点可以走,也就是这样
//他才能走边整个地图。
//所以主要有几个点,就是它选定了方向之后就一直开始走,走到目的地,或者是没有路了,我们就回溯到上一个节点
//这也就是我们在dfs()之后又写东西的原因,也就是换个方向,还有一些其他的操作,比如这个题就是让你把那个数拿出来
//也就是再标记成没有用过
#include<stdio.h>
#include<math.h>
#include<cstring>
int vis[30],ans[30];
int n;
int prime[30]={0,0};
//素数的打表,我们从下往上走,2 4 6 8
//                         3 6 9 12
//                         5 10 15
//也就是说素数是第一个就是开头还没有来的及繁衍
void  is_prime()//筛选法统计素数--埃拉托色尼筛
{
    int i,j;
    for(i=2;i<=50;i++)
        prime[i]=1;
    for(i=2;i*i<=50;i++)//改成i*i
    {
        if(prime[i])
        {
            for(j=i*i;j<=50;j+=i)//改成i*i
                prime[j]=0;
        }
    }
}

void printf_ans()
{
    int i;
    for(i=1;i<n;i++)
        printf("%d ",ans[i]);
    printf("%d\n",ans[i]);
}

void  dfs(int step)
{
    //这是递归的终点,也就是已经填完了所有的位置,这时候再去看看首尾是不是组成素数
    if(step==n&&prime[ans[n]+1])//找完n个数,然后按照题目要求看看是不是首尾是素数
    {
        printf_ans();
        return;
    }
    else
    {
        //这就是去尝试往哪个方向走,也就是说这个点可以填几
        for(int i=2;i<=n;i++)
        {   //这个点没有在前面被填过,那么我们再去看看它是不是满足题目要求,和当前的位置上的数组成素数
            if(!vis[i]&&prime[i+ans[step]])
            {
                //可以我们就先将下一个位置上填上数
                ans[step+1]=i;
                //标记上这个数,已经用过
                vis[i]=1;
                //然后再去深搜下一个位置,将现在的已经填完的位置传过去,也就是所谓的不撞南墙不回头
                dfs(step+1);
                //这就是所谓的回溯到该点之后的操作,把这个数拿出来,放到一边
                vis[i]=0;
            }
        }
    }
}

int main()
{
   int cn=1;
   is_prime();//这个表必须得启动
   while(~scanf("%d",&n))
   {
       memset(vis,0,sizeof(vis));
       ans[1]=1;
       printf("Case %d:\n",cn++);
       dfs(1);//上传第一个位置
       printf("\n");
   }
   return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值