HDU 1016 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.
一个有n个数组成的环组成圆圈所示图。把自然数1,2,……、n分别放到每个圆里并且在两个相邻的圈子里数字的总和应该是一个质数。
Note: the number of first circle should always be 1. 

注:第一圈的数量应该是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.
输出格式像下面示例所示。每一行代表一个系列的圆的数字环从1开始顺时针和逆时针方向。数字的顺序必须满足上述要求。以词法顺序打印解决方案。
You are to write a program that completes above process.
你要编写一个程序,完成上述过程。
Print a blank line after each case.

每个案例后打印一个空行。

Sample

Input

6

8

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

 思路:

这道题刚拿到的时候有点懵,感觉工作量蛮大的,既要将n个数字排进圈圈里,还要满足相邻的两个圈里的数相加要是质数。可以知道的是第一个数必是1,所以的先从1开始入手,将数组清零后,就先把1标记已使用,再进入DFS回溯搜索一下有没有符合条件且没用过的数字进行输出并标记已使用,在进行搜索下一个数,由此循环,将可能的情况全部输出。

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;

int num[100100],vis[100100];
int n;
void dfs(int c);
int prim(int x);

int main(void){
    int k=1;
    while(scanf("%d",&n)!=EOF){
        memset(vis,0,sizeof(vis));//每一次的n,都要讲标记数组清零
        num[0]=1;
        vis[1]=1;//标记1被使用
        printf("Case %d:\n",k++);//输出前面的序号
        dfs(1);
        printf("\n");
    }
    return 0;
}
 
int prim(int x){//判断是否为素数
    for(int i=2;i*i<=x;i++)
    if(x%i==0)
    return 0;

    return 1;
}

void dfs(int c){//从1开始搜索
    if(c==n&&prim(num[n-1]+1)){//如果排到了最后一位且与第一位的和满足条件
        printf("1");//保证第一位是1;
        for(int i=1;i<n;i++)//实际从num[]的第二位输出
        printf(" %d",num[i]);//一直到n-1位
        printf("\n");
    }

    if(c==n) return ;

    for(int i=2;i<=n;i++){
        if(!vis[i]&&prim(num[c-1]+i)){//满足与上一位和为素数,且数字没有被使用过
            num[c]=i;//放入这个满足条件的数
            vis[i]=1;//标记
            dfs(c+1);//搜索下一位
            vis[i]=0;
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值