HDU 1016 Prime Ring Problem DFS

来源:互联网 发布:网 网络手游交易网√ 编辑:程序博客网 时间:2024/06/05 02:01

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

68
 

Sample Output

Case 1:1 4 3 2 5 61 6 5 2 3 4Case 2:1 2 3 8 5 6 7 41 2 5 8 3 4 7 61 4 7 6 5 8 3 21 6 7 4 3 8 5 2

搜索素数环

使用深搜,在每一环上对所有可使用数字进行搜索,并判断是否与前一数字之和为素数,

素数环的最后一个数字还要检查他与第一个数字和是否为素数

每次搜索到最后一环就进行输出

还要注意输出的格式

代码如下:

#include<cstdio>#include<iostream>#include<cstdlib>#include<cmath>using namespace std;bool b[21]={0};int total=0,a[21]={0};int n;void search(int);int print();bool pd(int,int);int main(){    while(cin>>n)    {        cout<<"Case "<<++total<<":"<<endl;        a[1]=1;        search(2);        cout<<endl;        }}void search(int t){    if (t==n+1) {if (pd(a[n],a[1]))print();return;}    int i;    for (i=2;i<=n;i++)     if (pd(a[t-1],i)&&(!b[i]))      {         a[t]=i;         b[i]=1;         search(t+1);         a[t]=0;         b[i]=0;      }      return;}int print(){   for (int j=1;j<n;j++)     cout<<a[j]<<" ";     cout<<a[n]<<endl;  }bool pd(int x,int y){    int k=2,i=x+y;    while (k<=sqrt(i)&&i%k!=0) k++;    if (k>sqrt(i)) return 1;       else return 0;}

原创粉丝点击