博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Prime Ring Problem
阅读量:7211 次
发布时间:2019-06-29

本文共 1620 字,大约阅读时间需要 5 分钟。

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.
Prime <wbr>Ring <wbr>Problem

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;让你写出一个素数环,要求相邻两个数(顺逆时针)和是素数,输出的时候第一个永远是一;
解题思路:按照递归求全排列的思想,从第2个开始递归一直到最后一位,并且首尾也是素数才算是搜索完成;
感悟:一开始我还以为得剪纸,但是只有20个数,一次就过了;
代码:
#include
#include
#include
#include
#define maxn 25
using namespace std;
int ans[maxn],visit[maxn],n;
int Prime(int a)
{
    for(int i=2;i<=sqrt(a);i++)
        if(a%i==0)
            return 0;
    return 1;
}
void dfs(int cur)
{
    if(cur==n&&Prime(ans[0]+ans[n-1]))//递归到最后一位,并且首尾也能是素数
    {
        for(int i=0;i
            printf("%d ",ans[i]);
        printf("%d\n",ans[n-1]);
    }
    else
    {
        for(int i=2;i<=n;i++)
        {
            if(!visit[i]&&Prime(i+ans[cur-1]))//这个数没用过并且相邻的是素数
            {
                ans[cur]=i;
                visit[i]=1;
                dfs(cur+1);
                visit[i]=0;
            }
        }
    }
}
int main()
{
    //freopen("in.txt", "r", stdin);
    int s=1;
    memset(visit,0,sizeof(visit));
    while(~scanf("%d",&n)&&n)
    {
        for(int i=0;i
            ans[i]=i+1;
        printf("Case %d:\n",s++);
        dfs(1);
        printf("\n");
    }
}

转载于:https://www.cnblogs.com/wuwangchuxin0924/p/5781611.html

你可能感兴趣的文章
【WPF】动态设置Binding的ConverterParameter转换器参数
查看>>
Nginx配置教程
查看>>
linux中查看和开放端口
查看>>
poj3181 Dollar Dayz
查看>>
求助下 Ubuntu 15.10(64 位)下安装 pyspider 下的问题 - V2EX
查看>>
SQL Server外连接、内连接、交叉连接
查看>>
Ajax-jQuery_Ajax_实例 ($.ajax、$.post、$.get)
查看>>
Python实现web动态服务器
查看>>
新客户上云 –虚拟机及相关服务常见问题集锦
查看>>
IntelliJ Idea 常用快捷键列表
查看>>
各数据库连接配置与maven依赖安装
查看>>
Linux(centOS)手动安装删除Apache+MySQL+PHP+Memcached原创无错版
查看>>
Nginx的启动(start),停止(stop)命令
查看>>
代码生成工具更新--快速生成Winform框架的界面项目
查看>>
Jquery根据JSON生成Table
查看>>
[Oracle]Sqlplus 中使用 new_value
查看>>
【HTTP】 认证和单点登录 【瞎写的…】
查看>>
微信小程序-上传多张图片加进度条(支持预览、删除)
查看>>
Java基础-SSM之mybatis快速入门篇
查看>>
error C2220: 警告被视为错误 - 没有生成“object”文件
查看>>