• HDU 1016.Prime Ring Problem-素数环,相邻两数和为素数-DFS


    Prime Ring Problem

    Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
    Total Submission(s): 67252    Accepted Submission(s): 28829


    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
     
    Source
     
     
     
     
     
    代码:
     1 #include<cstdio>
     2 #include<iostream>
     3 #include<cstring>
     4 #include<algorithm>
     5 using namespace std;
     6 int prime[]={2,3,5,7,11,13,17,19,23,29,31,37};
     7 bool isprime[40];
     8 bool used[21];
     9 int num[21],n;
    10 bool dfs(int count,int cur){ //深度优先搜索
    11     num[count]=cur;
    12     if(count==n-1){
    13         if(!isprime[cur+1])return false;
    14         for(int i=0;i<n-1;i++)
    15             printf("%d ",num[i]);
    16         printf("%d
    ",num[n-1]);
    17         return false;
    18     }
    19     for(int i=2;i<=n;i++){
    20         if(used[i])continue;
    21         used[i]=true;
    22         if(isprime[cur+i]&&dfs(count+1,i))
    23             return true;
    24         used[i]=false;
    25     }
    26     return false;
    27 }
    28 int main(){
    29     memset(isprime,false,sizeof(isprime));
    30     for(int i=0;i<12;i++)
    31         isprime[prime[i]]=true;//存在素数isprime数组标记为1
    32     int Case=1;
    33     while(~scanf("%d",&n)){
    34         printf("Case %d:
    ",Case++);
    35         memset(used,false,sizeof(used));
    36         used[1]=true;
    37         dfs(0,1);
    38         printf("
    ");
    39     }
    40     return 0;
    41 }
  • 相关阅读:
    maven_常用命令
    tomcat_server.xml常用配置
    tomcat线程池原理
    Tomcat处理HTTP请求原理&线程池
    javaweb-javaScript(一)
    javaweb-html快速入门
    javaweb-css
    javaweb-单元测试与注解
    javaweb-文件的上传下载
    javaweb-jsp开发模式+JSON插件
  • 原文地址:https://www.cnblogs.com/ZERO-/p/9740483.html
Copyright © 2020-2023  润新知