JD 题目1459:Prime ring problem (dfs)

来源:互联网 发布:mac mysql管理工具 编辑:程序博客网 时间:2024/05/20 18:49

OJ题目:click here~~

题目分析:1……n 形成一个环,相邻的两个数加起来要是素数。

这么简单的题目也贴,目的还是不纯呐。。鄙视

#include <stdio.h>#include <string.h>#include <math.h>#include <iostream>using namespace std ;int x[20] , vis[20] , n ;bool flag ;void output(){    printf("%d" , 1) ;    for(int i = 2;i <= n;i++)        printf(" %d" , x[i]) ;    puts("") ;}bool Is_prime(int x){    for(int i = 2;i * i <= x;i++){        if(x%i == 0) return false ;    }    return true ;}void dfs(int t){    if(t == n + 1){        if(Is_prime(x[n] + 1)){            output() ;            return ;        }        else            return ;    }    for(int i = 2;i <= n;i++){        if(vis[i]) continue ;        if(Is_prime(x[t - 1] + i)){            x[t] = i ;            vis[i] = -1;            dfs(t + 1) ;            vis[i] = 0 ;        }    }}int main(){    int i , j , T = 1;    while(cin >> n){        x[1] = 1 ;        vis[1] = -1 ;        printf("Case %d:\n" , T++) ;        dfs(2) ;        puts("");    }    return 0 ;}


0 0