HDU 1016 素数环(DFS)

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
题目大意:输入一个整数n,然后由1-n这n个数构成一个环,环的要求是相邻两个元素之和都为素数,然后以1开头按字典序先顺时针输出所有解,然后逆时针输出解。

问题分析

  这是一道深度搜索题,题中要求字典序输出,因此在深度遍历时就从1-n开始遍历,这样依次找到的解一定是字典序。对于顺时针和逆时针输出可以不用管,只需找出所有顺时针解即可,因为一个顺时针解的逆时针输出必然是顺时针的另一个解,又由于是字典序,所以一定和顺时针输出的排列顺序相同。
  引入一个数组vis[j],初始化为全0,用于标记数字j是否被访问,若是,则为1,否则为0(因为每个数只能用一次),再引入数组a[ ],用来存储素数环结果,当满足条件时,输出素数环即可,下面是实现代码:
  注意:这里有个坑,就是输出素数环时只能在n个元素之间有空格,末尾不能有空格,否则会格式错误。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int vis[30];//标记是否访问
int n;
int a[30];
bool is_prime(int a)//判断素数
{
    if(a==1)return false;
    for(int i=2;i*i<=a;i++)
        if(a%i==0)return false;
    return true;
}
void dfs(int k,int cnt)
{
    if(cnt==n&&is_prime(k+1))
    {//当个数等于n,并且与第一个元素和也为素数时,输出
        for(int i=0;i<n;i++)
            if(i<n-1)printf("%d ",a[i]);
            else printf("%d\n",a[i]);
    }
    for(int i=1;i<=n;i++)//从小到大依次搜索(保证字典序)
    {
        if(!vis[i]&&is_prime(i+k))
        {
        	a[cnt]=i;//记录素数环
	        vis[i]=1;//标记为1,表示已经访问
	        dfs(i,cnt+1);//深度搜索,回溯
	        vis[i]=0;//恢复标记
		}
    }
}
int main()
{
    int i=0;
    while(scanf("%d",&n)!=EOF)
    {
        memset(vis,0,sizeof(vis));
        memset(a,0,sizeof(a));
        printf("Case %d:\n",++i);
        vis[1]=1;a[0]=1;
        dfs(1,1);
        printf("\n");
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值