hdu1016 Prime Ring Problem

//经典搜索题 

#include <iostream>

#include <cstring>

using namespace std;



int primelist[38] = {0,0,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1};

//素数表, 

int n;

int A[21];   

//存放序列结果 

int vis[21];

//访问标记 



void DFS(int cur)

{

     if(cur == n && primelist[A[n-1]+A[0]])    //结束条件 

     {

            cout<<A[0];

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

            {

                    cout<<" "<<A[i];       

            }

            cout<<endl;

     }

     else

     {

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

            {

                    if(!vis[i] && primelist[i + A[cur-1]])   //如果i没有用过并且能与前面的数和成素数 

                    {

                              A[cur] = i;    //标记i已访问 

                              vis[i] = 1;    //将i加入结果序列 

                              DFS(cur+1);    //递归访问 

                              vis[i] = 0;    //回溯法标准框架去掉标记 

                    }

            }

     }

}



int main()

{

    int count = 0;

    A[0] = 1;

    while(cin>>n)

    {

          memset(vis,0,sizeof(vis));

          count++;

          cout<<"Case "<<count<<":"<<endl;

          DFS(1);

          cout<<endl;

    }

    return 0;

}


刘汝佳白书上的题目,回溯法标准框架
Fenice CSDN

你可能感兴趣的:(Prim)