zstu4028——DFS+回溯——素数和环

Description

把前n个正整数摆成1个环,如果环中所有相邻的2个数之和都是1个素数,该环称为1个n项素数和环。 输入1个整数n,输出共有多少种

Input

输入一个正整数n

Output

输出环的个数,要求环的第一个数字是1

Sample Input

4

Sample Output

2

HINT

大意:回溯,要会写dfs得到全排列

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 66666;
int vis[maxn];
int a[maxn];
void dfs(int step)
{
    if(step == n + 1){
        for(int i = 1; i <=  n; i++)
            printf("%d",a[i]);
            return ;
    }
    else {
        for(int i = 1; i <= n ; i++){
            if(!vis[i]){
                vis[i] = 1;
                a[step] = i;
                dfs(step+1);
                vis[i] = 0;
            }
        }
    }
}

 AC代码

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 666666;
int vis[maxn];
int n,cout;
int a[maxn];
int prim(int n){
    int i;
    for( i = 2; i*i <= n ;i++){
        if(n%i == 0)
            break;
    }
    if(i*i > n)
    return 1;
     return 0;
}
void dfs(int step)
{
    if(step == n+1){
        int i;
        //for(int j = 1; j <= n ;j++)
        //    printf("%d",a[j]);
        //    puts("");
        for( i = 1; i <= n ;i++){
            int x = a[i],y = a[i+1];
            if(i == n){
                y = a[1];
            }
            if(prim(x+y) == 0){
                break;
            }
        }
        if(i > n) {
        //for(int i = 1; i <= n ;i++)
        //    printf("%d",a[i]);
       // puts("");
       // printf("%d %d\n",a[4]+a[5],prim(a[4]+a[5]));
        cout++;
 
        }
    }
    for(int i = 2; i <= n ; i++){
        if(!vis[i]){
            vis[i] = 1;
            a[step] = i;
            dfs(step+1);
            vis[i] = 0;
        }
    }
}
int main()
{
    a[1] = 1;
    while(~scanf("%d",&n)){
        if(n%2 == 1)
            printf("0\n");
        else {
        cout = 0;
        dfs(2);
        printf("%d\n",cout);
        }
    }
    return 0;
}
 

  

posted @ 2015-05-19 16:58  Painting、时光  阅读(453)  评论(0编辑  收藏  举报