搜索 Q - 素数环(dfs)

本文介绍了一种基于深度优先搜索的算法,用于解决素数环问题。该问题要求将1到n的数字放置在一个环形结构中,使得任意相邻两数之和为素数,并且首位数字固定为1。文章提供了完整的C++实现代码。

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 的数字排序 ,使之满足素数环的条件。
思路:一道深度搜索, 要注意的是开头的永远是1 。
Code:
#if 0
#include<iostream>
#include<cmath>
using namespace std;
int N , toal;
bool pd[21] ;
int ret[21] ;
int prime(int a ,int b) 
{
  int x=a+b ,cnt=2;
  int sqrx=sqrt(x) ;
 
while(cnt<=sqrx&&x%cnt!=0) cnt++;
if(cnt>sqrx) return 1;
else return 0 ;
}
int show()
{
 for(int i=1 ; i < N ;i++)
   cout << ret[i]<<" " ;
   cout << ret[N]<< endl;
 
}
int dfs(int t,int n) //t代表第几层 
{
 int i  ;
 
 for(i = 1 ; i <= n ; i++)
 {
  if(prime(ret[t-1],i) && !pd[i])
  {
   ret[t]=i;
   pd[i]=1;
  if(t==n)
 {
  if(prime(ret[n],ret[1])&&ret[1]==1) show();
 }
        else    dfs(t+1,n) ;
         pd[i]=0;
  }
 }
       
 
}
int main()
{
   while(cin>>N)
   {
    toal++ ;
    cout << "Case "<<toal<<":"<<endl;
    dfs(1,N) ;
    cout << endl;
 }
 
 } 

#endif




评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值