hdu1016(素数环剪枝dfs)

题意:n<20范围,搜一个全排列,满足素数环,相邻两个数字和为素数,最后一位和第一位之和也是素数。
剪枝:每一位都先先判断再搜索。


#include <fstream>
#include <iostream>
#include <string>
#include <complex>
#include <math.h>
#include <set>
#include <vector>
#include <map>
#include <queue>
#include <stdio.h>
#include <stack>
#include <algorithm>
#include <list>
#include <ctime>
#include <cstring>
#include <ctime>
#include <assert.h>

#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define eps 1e-8
#define M_PI 3.141592653589793

typedef long long ll;
const ll mod=1000000007;
const int inf=99999999;
ll powmod(ll a,ll b) {ll res=1;a%=mod;for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
using namespace std;
int n,a[30],v[30],t,prime[41]={0,0,0,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,1,0,0,0,1,0,0,0};

void dfs(int cur)
{
   if(cur==n)
   {
       int flag=0;
       if(prime[a[n-1]+ a[0]])
       {
           //cout<<flag<<endl;
           for(int i=0;i<n-1;i++) printf("%d ",a[i]);
           printf("%d\n",a[n-1]);
       }
       return;
   }
   else
   {
       for(int i=2;i<=n;i++)
       {
           if(!v[i])
           {
               if(prime[a[cur-1]+i])
               {
                  a[cur]=i;
                  v[i]=1;
                  dfs(cur+1);
                  v[i]=0;
               }
           }
       }
   }
}

int main()
{
    int ff=0;
    while(~scanf("%d",&n))
    {
        printf("Case %d:\n",++t);
        memset(v,0,sizeof(0));
        a[0]=1;

        dfs(1);
        printf("\n");
        //cout<<judge(9)<<endl;
    }
}

你可能感兴趣的:(hdu1016(素数环剪枝dfs))