zoukankan      html  css  js  c++  java
  • hdu 1016 Prime Ring Problem(深度优先搜索)

    Prime Ring Problem

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

    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
     
     
    题意:输入一个 n 找出1~n的组合,使得相邻两个数之和为素数;
    分析:预处理40之间的素数,然后回溯;
     1 #include<iostream>
     2 #include<cstring>
     3 #define N 25
     4 #define M 40
     5 using namespace std;
     6 
     7 bool is_prime[M],visited[N];
     8 int n,test,ans[N];
     9 
    10 void work(int k)
    11 {
    12     int i;
    13     if(k==n+1)
    14     {
    15         if(!is_prime[ans[n]+ans[1]]) return ;
    16         for(i=1;i<=n-1;i++)
    17             cout<<ans[i]<<" ";
    18         cout<<ans[i]<<endl;
    19         return ;
    20     }
    21     for(i=2;i<=n;i++)
    22     {
    23         if(!visited[i]&&is_prime[ans[k-1]+i])
    24         {
    25             visited[i]=true;
    26             ans[k]=i;
    27             work(k+1);
    28             visited[i]=false;
    29         }
    30     }
    31 }
    32 
    33 bool prime(int n)
    34 {
    35     if(n==1) return false;
    36     if(n==2||n==3) return true;
    37     int i;
    38     for(i=2;i<n;i++)
    39         if(n%i==0)
    40             return false;
    41     return true;
    42 }
    43 
    44 int main()
    45 {
    46     int i;test=1;
    47     for(i=1;i<M;i++) is_prime[i]=prime(i);
    48     while(cin>>n)
    49     {
    50         ans[1]=1;
    51         memset(visited,false,sizeof(visited));
    52         cout<<"Case "<<test<<":"<<endl;
    53         work(2);
    54         test++;
    55         cout<<endl;
    56     }
    57     return 0;
    58 }
    View Code
  • 相关阅读:
    再也不买仙剑正版盘了
    如果能边睡觉边上网多好
    不服
    <转>猛兽多是懒汉
    窗体中实现按 回车键 跳到下一个可选的TabIndex控件
    c# 索引器基础理论
    软件加密技术和注册机制入门介绍
    c# 属性 
    异常的一些基础知识
    关于MessageBox.Show的使用
  • 原文地址:https://www.cnblogs.com/wft1990/p/5174996.html
Copyright © 2011-2022 走看看