HDU--杭电--1016--Prime Ring Problem--深度优先搜索--此类中的水题

Prime Ring Problem

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 19807    Accepted Submission(s): 8858


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

 

#include
#include
using namespace
std;
int
n,sushu[100]={0},huan[10]={0,1},see[22];  //see数组用来标记此数字是否可用,sushu数组是素数表,huan数组是记录素数环
void
DFS(int s,int k)
{

    int
i;
    if
(
s>n)
    {

        if
(
sushu[huan[1]+huan[s-1]])
        {

            for
(
i=1;i<=n;i++)
            {

                if
(
i>1)cout<<" ";
                cout<<huan[i];
            }
cout<<endl;
        }

        else return
;
    }

    for
(
i=2;i<=n;i++)
    {

        if
(
k)  //如果是第一次递归,那么把see数组初始化,不过我现在觉得没意义——!这个可以不要,删除没过的话找我是问
            for
(int
j=1;j<22;j++)
                see[j]=1;
        if
(
sushu[i+huan[s-1]]&&see[i])
        {

            huan[s]=i;//把i装进素数环的相应位置
            see[i]=0;
            DFS(s+1,0);  //指向下一个空洞-—-!并且用0标记以后的都不是第一次的递归
            see[i]=1;
        }
    }
}

int
main (void)
{

    int
i,j,k,l=1;
    for
(
i=1;i<100;i+=2)sushu[i]=1;  //虽然数量是比较少,不过我还是觉得打表爽一些
    sushu[1]=0;sushu[2]=1;
    for
(
i=3;i<100;i++)
        for
(
j=i+i;j<100;j+=i)
            sushu[j]=0;
        while
(
cin>>n)
        {

            cout<<"Case "<<l++<<":"<<endl;
            if
(
n==1)cout<<"1"<<endl;//经过无意间证明,其实不用这一句,而且要的话其实是错的,不信你贴我家代码输入1啊
            DFS(2,1);  //从环内第二个洞开始填,用1标记第一次的那个递归
            cout<<endl;
        }

    return
0;
}

你可能感兴趣的:(深搜)