Hdu1016 Prime Ring Problem 【简单dfs】

http://acm.hdu.edu.cn/showproblem.php?pid=1016

题目大意:找不所有第一个数是1,相邻两数之和是素数的n元环。

直接dfs

 

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <cmath>
#include <queue>
using namespace std;
template <class T> void checkmin(T &t,T x) {if(x < t) t = x;}
template <class T> void checkmax(T &t,T x) {if(x > t) t = x;}
template <class T> void _checkmin(T &t,T x) {if(t==-1) t = x; if(x < t) t = x;}
template <class T> void _checkmax(T &t,T x) {if(t==-1) t = x; if(x > t) t = x;}
typedef pair <int,int> PII;
typedef pair <double,double> PDD;
typedef long long ll;
#define foreach(it,v) for(__typeof((v).begin()) it = (v).begin(); it != (v).end ; it ++)
const int N = 33;
bool vis[N];
int a[N] , b[N] , n;
void init() {
    a[2] = a[3] = a[5] = a[7] = a[11] = a[13] = a[17] = a[19] = a[23] = a[29] = 1;
}
void dfs(int dep , int pre , int n) {
    if(dep == n) {
        for(int i=1;i<=n;i++) {
            if(!vis[i]) if(a[i+pre] && a[i+1]) {
                b[dep] = i;
                printf("1");
                for(int i=2;i<=n;i++) printf(" %d",b[i]);
                puts("");
                return;
            }
        }
        return;
    }
    for(int i=1;i<=n;i++) {
        if(!vis[i] && a[i+pre]) {
            vis[i] = 1;
            b[dep] = i;
            dfs(dep+1,i,n);
            vis[i] = 0;
        }
    }
}
int main() {
    int cas = 1;
    init();
    while(~scanf("%d",&n)) {
        printf("Case %d:\n",cas++);
        memset(vis,0,sizeof(vis));
        vis[1] = 1;
        b[1] = 1;
        dfs(2,1,n);
        puts("");
    }
    return 0;
}

 

 

posted @ 2013-03-28 23:40  aiiYuu  阅读(171)  评论(0)    收藏  举报