• HDU 1016 Prime Ring Problem(dfs)


    Problem Description
    A ring is compose of n circles as shown in diagram. Put natural number 1, 2, ..., n into each circle separately, and the sum of numbers in two adjacent circles should be a prime.
    Note: the number of first circle should always be 1.

     
    Input
    n (0 < n < 20).
     
    Output
    The output format is shown as sample below. Each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above requirements. Print solutions in lexicographical order.
    You are to write a program that completes above process.
    Print a blank line after each case.
     
    Sample Input
    6 8
     
    Sample Output
    Case 1:
    1 4 3 2 5 6
    1 6 5 2 3 4
    Case 2:
    1 2 3 8 5 6 7 4
    1 2 5 8 3 4 7 6
    1 4 7 6 5 8 3 2
    1 6 7 4 3 8 5 2
     
    用深搜回溯,一个一个搜下去
     1 #include<cstdio>
     2 #include<string.h>
     3 #include<cmath>
     4 #include<algorithm>
     5 using namespace std;
     6 int n,cnt;
     7 int prime(int x){//判断素数 
     8     if(n==1)
     9         return 0;
    10     if(n==2)
    11         return 1;
    12     for(int i=2;i<=floor(sqrt(x));i++){
    13         if(x%i==0)
    14             return 0;
    15     }
    16     return 1;
    17 }
    18 
    19 int vis[30],a[30];
    20 void dfs(int x){
    21     if(x==n&&prime(a[n]+1)){//如果正好轮了n个数,且相邻之和都为素数,输出 
    22         for(int i=1;i<=n-1;i++){
    23             printf("%d ",a[i]);
    24         }    
    25         printf("%d
    ",a[n]);    
    26     }
    27     for(int i=2;i<=n;i++){ //从2-n一个一个试下去 
    28         a[cnt]=i;
    29         if(prime(a[cnt]+a[cnt-1])&&vis[i]==0){ //然后是素数且没有用过就继续 
    30             vis[i]=1;//标记用过 
    31             cnt++;
    32             dfs(x+1);
    33             vis[i]=0;//回溯 
    34             cnt--;
    35         }
    36     }
    37 }
    38 
    39 int main(){
    40     int q=1;
    41     while(scanf("%d",&n)!=EOF){
    42         printf("Case %d:
    ",q++);
    43         memset(vis,0,sizeof(vis));
    44         memset(a,0,sizeof(0));
    45         vis[1]=1;
    46         a[1]=1;
    47         cnt=2;
    48         dfs(1);        
    49         printf("
    ");
    50     }
    51     return 0; 
    52 }
  • 相关阅读:
    [AS3 3D Demo] Stage3D学习过程中开发的3个Demo
    NGUI学习笔记(一):官方视频学习记录
    关于继承MonoBehaviour的一些记录
    Jquery js框架使用
    Highcharts 图表js框架
    js上传控件 plupload 使用记录
    关于 web中 使用 java.net.URLEncoder.encode 要编码两次呢 , js的encodeURIComponent 同理
    跑测试没有web环境的情况
    sitemesh 学习之 meta 引入
    sitemesh 2.4 装饰器学习
  • 原文地址:https://www.cnblogs.com/cake-lover-77/p/10197652.html
Copyright © 2020-2023  润新知